It depends, better in what sense?
If you value short clean code above all else, then this is good. Here's an example:
class Dog {
private String name;
private Type type;
public static enum Type {
large, medium, small;
}
This works because uninitialized Objects start off as null. Also empty constructors need not be specified.
If you value clarity but still want to keep the code as short as possible, then
class Dog {
private String name = null;
private Type type = null;
public Dog() {}
public static enum Type {
large, medium, small;
}
}
is better because other (less experienced) devs can see clearly what the values are, and the constructor is clearly defined.
Initializing constant values in the constructor also has its own benefits:
- Clearly separate declarations from values/logic
- Flexibility to add logic in future when needed (extensibility)
Just evaluate the pros and cons for each situation, see what you like. The only exception is when you work with an existing codebase; in this case keep to the conventions / style guide.
nullanyway.null(although in a very special case).