In Java, it is not mandatory to initialize class attributes. Primitive types are given default values and objects are null
automatically.
However, variables declared inside the body of a method do not receive default values and the compiler will complain if you try to use them without assigning a value before.
However, it is often a bad practice to allow a program to run in an inconsistent state. Good practice is always trying to ensure that the proper values have been set before using them.
The way to do this in class attributes is whenever possible to initialize the value in the statement, when this makes sense. Whenever possible, still use attributes with the final
modifier, which forces the programmer to initialize them sometime to the end of the constructor method.
Example:
class Configuracao {
private final String diretorio;
public Configuracao(Properties properties) {
this.diretorio = properties.getProperty("diretorio", "/tmp");
}
}
Already variables within method, avoid completely initializing them with random values only to silence the compiler, rather let it help you to not leave any loopholes in your program.
Bad example:
String getNome() {
String nome = "Valor que nunca deve ser usado";
if (condicao()) nome = getNomeDeVerdade();
return nome;
}
In the above example, if the condition is not satisfied, the value that should not exist will be returned. I know it sounds ridiculous, but I've seen several versions of it out there because someone followed the "hint" of the IDE or compiler telling to initialize the variable.
The correct thing would be not to initialize the variable and treat the other case specifically:
String getNome() throws Exception {
String nome;
if (condicao()) nome = getNomeDeVerdade();
else throw new Exception("Nome não pode ser determinado");
return nome;
}
On the other hand, if a value is not always returned, use Optional
and not null
or ""
to represent such absence.
Example:
Optional<String> getNome() throws Exception {
return condicao() ?
Optional.of(getNomeDeVerdade()) :
Optional.empty();
}
Then call the method and check if there is a value returned:
Optional<String> nome = metodo();
if (nome.isPresent()) {
fazerAlgumaCoisa(nome.ge());
} else {
tratarSituacaoSemNome();
}
This type of technique virtually eliminates extraneous behavior of the system caused by unexpected values, in addition to the greater cause of problems, NullPointerException
.