The most appropriate way to ensure that the attributes of an object are properly defined is to force their initialization during the initialization of the object.
It is good practice that all attributes of an object are final
. Attributes final
must be initialized until the object constructor is finished.
Example:
public class MeuObjeto {
private final String atributo1;
private final int atributo2;
public MeuObjeto(String atributo1, int atributo 2) {
this.atributo1 = atributo1;
this.atributo2 = atributo2;
}
//getters
}
If, for some reason, your object cannot be immutable, then you will not be able to use the final
, but can still force all attributes to be initialized using the constructor.
public class MeuObjeto {
private String atributo1;
private int atributo2;
public MeuObjeto(String atributo1, int atributo 2) {
this.atributo1 = atributo1;
this.atributo2 = atributo2;
}
//getters
//setters
}
However, keep in mind that mutable objects are common cause of problems in various scenarios and not only for competition as is often thought.
All this "problem" described in the question, related to having an object with an undefined state, actually only exists due to a "weak" model of objects that allows them to reach that state.
For each scenario there is a different strategy to model well an object and the general rule is, avoid changing what does not need to be changed.