The most appropriate way to ensure that the attributes of an object are properly defined is by forcing them to initialize at startup.
It is a good practice for all attributes of an object to be final
. final
attributes must be initialized until the constructor of the object finishes.
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 can not be immutable, then you will not be able to use final
, but you 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 a common cause of problems in many scenarios and not just for competition as you might think.
All this "problem" described in the question, related to having an object with undefined state, actually exists only because of a "weak" model of objects that allows them to arrive in this state.
For each scenario there is a different strategy for modeling an object well and the general rule is, avoid leaving changeable what does not need to be changed.