Should I initialize strings (or objects in general) with null?

15

I have noticed that a common practice among programmers is to initialize an attribute of a class with null . Is this a good practice or not? Is there any difference between initializing with null or not initializing "at all"? Example:

public class MinhaClasse {

       String str1 = null;

}
    
asked by anonymous 15.01.2016 / 14:28

4 answers

11

No difference, the compiler initializes class attributes with null by default. In case of primitive types, it initializes with the default value (false for boolean and 0 for double, long, int ...)

    
15.01.2016 / 14:34
7

In my opinion you should not. Objectively, whatever. It's just being redundant. I do not think it's good until you prove to me that in one place it's the best thing to do.

Almost always failing to initialize a variable is bad. Why leave what can you do now? Maybe because you're declaring variables too early. I see a lot of code that declares all variables and then goes using it. This technique is archaic. The modern style is to declare the variable as close as possible to where it will be used. Of course in some cases it may make sense to declare the variable and not initialize. But it's rare.

Whenever possible, initialize the objects with a value that serves something. We can not strictly say that saying that the variable is null is initializing it. But there are cases that leave it as null may indicate something useful for the code .

It does not make sense to initialize primitive variables if what you need is the default value of it. Writing int x = 0; is the same as writing int x ;. Of course it might be interesting to do this to make it explicit that you want the 0 consciously. It is the same as null ., After all this is the default value of objects by reference .

    
15.01.2016 / 14:56
7

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 .

    
16.01.2016 / 00:51
5
  

I do not think it's a good practice to leave it explicit or not, even   in cases of local scope in methods, where in most cases it is   initialize.

The reason is to leave open the possibility that we have to deal with the Exception most common in development, NullPointerException .

The good practice that I know is always or whenever possible initialize variable , be it primitive type or an object .

So not having a null even in cases of optional attributes , therefore avoiding NullPointerException .

Ex:

public class Endereco {

   private String rua = "";
   private int numero = 0;

   //getters e setters
}
    
15.01.2016 / 14:48