In Java, it is not mandatory to initialize class attributes. Primitive types receive default values and objects are null
automatically.
However, variables declared within 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 generally bad practice to allow a program to run in an inconsistent state. Good practice is always try to ensure that the appropriate 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 modifier final
, that require the programmer to initialize them at some point until 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 the method, avoid completely initializing them with random values only to silence the compiler, before letting it help not leave gaps 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 around because someone followed the "hint" from the IDE or compiler saying to initialize the variable.
The correct would be not 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 whoever calls the method should check if there is a value returned:
Optional<String> nome = metodo();
if (nome.isPresent()) {
fazerAlgumaCoisa(nome.ge());
} else {
tratarSituacaoSemNome();
}
This type of technique practically eliminates strange system behaviors caused by unexpected values, in addition to the biggest caused by problems, the NullPointerException
.
It can only be common practice among programmers who do not yet understand how the language works. Declaring a field without specifying value is already a way of specifying that you want the default assignment; so writing code for that is repeating yourself. For variables declared in the body of methods, it may be useful to explicitly assign the default value (and this explicit assignment may even be required by the compiler).
– Caffé