Stylistically is it better to initialise Java fields within a constructor or at the point where the field is declared? For example:
public class Foo {
private final List<String> l;
public Foo() {
this.l = new LinkedList<String>();
}
}
… or
public class Foo {
private final List<String> l = new LinkedList<String>();
}
I have typically favoured the former as it seemed clearer. However, the latter obviously results in more compact code.
My rule of thumb is:
Put it at the point of the declaration if
otherwise, put it in the constructor.
Usually I follow the official Java Coding Conventions strictly. In this particular case the convention doesn’t say anything about it, so it’s up to each programmer to decide. Which ever you pick however, you probably want to be consistent with your choice.