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

Goto in Java

So there is no GOTO in java, although I believe it is a reserved keyword.

However, you can do this …


    while ( ... ) {
         level1:
         for ( ... ) {
              for( ... ) {
                   break level1;
              }
         }
    }

It allows you to break out of a set of nested loops back to whichever level you like.

Share