Initialisation inline or in Constructor ?

private Map<String, String> nodeValueMap = new HashMap<String, String>();
private Map<String, NodeHandler> nodeHandlers = new HashMap<String, NodeHandler>();			

Or

public MyClass() {
    this.nodeValueMap = new HashMap<String, String>();
    this.nodeHandlers = new HashMap<String, NodeHandler>();			
}

Well, I think I might have a rule of thumb… If you don’t actually have a constructor, then you should use inline instantiation. As soon as you need to do some more complex logic in the constructor (in the case above I might want to initialise the map with some objects) then move all the initialisers into the constructor ?

i.e. don’t have multiple patterns going on.

As an aside, a quick discussion with Alistair (of how big is my potato fame) reminded me of the fact that you can actually do an instance initialisation like:

{
    this.nodeValueMap = new HashMap<String, String>();
    this.nodeHandlers = new HashMap<String, NodeHandler>();			
}

Although what the case for doing so is im not sure, might be nice if you are making a STRUCT kind of object.

Also I didn’t realise that you can declare a class inside a method:

public void doSomething() {
    public class InnerClasss{
        public void sayHello() { System.out.println("hello");}
    }

    InnerClass inst = new InnerClass();
    inst.sayHello();
}

Alistair had used this for testing some reflection code, when he needed some test classes to work with.

Share

One thought on “Initialisation inline or in Constructor ?

  1. I’d say, use your constructor to inject dependencies, and nothing else. Complex logic of course goes in a factory, and inline initialisation removes clutter from the constructor.

    Inline init is well defined, and quite readable when you get used to it.

Comments are closed.