It completely depends on how the class should be used.
An example is value classes, which can often be immutable. Ideally, in this case, you should set the values ββin the constructor.
public final class Foo { private final String foo; public Foo(String foo) { this.foo = foo; } }
If there are really reasonable defaults, you can provide them at the point of declaration. This, as a rule, makes it pretty easy to see what the expected default value is. Of course, this does not work with leaf fields (as indicated above), since it is impossible to assign a different value.
Another consideration concerns the relative merits of initializing a constructor or mutator. Using constructor initialization ensures that the instance is never in an inconsistent state, while mutator initialization is often more flexible and provides an easier API.
In the initial comment on avoiding NPE
s, I would say that it is best to use it by initializing the constructor according to the code above.
ptomli
source share