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

Asked

Viewed 4,276 times

16

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

public class MinhaClasse {

       String str1 = null;

}
  • 1

    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).

4 answers

13


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

7

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.

  • utluiz always with excellent answers, very cool :) I have a question regarding the use of Optional in parameters, it is interesting to start making use to have a clearer semantics at the time perform the verification?

  • @Douglasgaldino This is worth a new question ;) - but in short there are some moments when it is worth using this in parameters. In most cases you can simply overload the method in a version without such parameter, but if it will force you to do ifs everywhere is better to use the Optional.

  • I understood, but I would also need to consider the overloads, to avoid multiple methods or this has little influence on the quality of the code?

  • @Douglasgaldino Yes, multiple methods, when very varied, are also not legal. If there are many variables, then there is another alternative, which is to create a specific type (class) to represent the parameters of the method. And then you can use a Pattern like Builder with method chaining to improve this. If you use a JAX-RS implementation, such as Jersey, you must have seen this at the time of returning a response, such as Response.ok(entity).status(200).build().

  • Yes, I know the Pattern Builder. I understand better now the process of dealing with multiple parameters. The purpose of the questions was only to try to improve the process, maintaining the quality even when an option ceases to be good at such time. Thanks :]

7

In my opinion it should not, objectively, whatever. It’s just that you’re being redundant and I don’t think this is good until you prove to me that in a certain place you’re the best at.

Almost always failing to initialize a variable is bad. Why leave for later what you can do now? Maybe because you’re declaring variables too soon. I see a lot of code that declares all variables and then goes on using them. 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 is rare.

Whenever possible initialize the objects with a value that serves something. We cannot strictly say that the variable is null is initiating her, but there are cases that leave her as null may indicate something useful for the code.

It doesn’t make much sense to initialize primitive variables if what you need is the value default of it. Write int x = 0; is the same thing as writing int x; (although in local variables this form is not accepted). Of course it can be interesting to do this to make it explicit that you want 0 consciously. It is the same case of null, after all this is the value default of objects by reference.

  • 1

    At certain times it is necessary to initialize explicitly the default value even if it is null because the compiler "Xia". But answering the question I don’t see how a good practice is to initialize the object as null (initialize when declassified in the scope of the equal class is in the description of the question) I never saw it that way, I always check the source code of the third-party libraries I add to my projects and I’ve never seen this, not that I remember.

  • Curious. Do you have any example that the compiler does this?

  • Yes, create a method that should return a String, declare the String and only initialize it within an if, and at the end of the method put to return that String. The Xia compiler for you to initialize the string, as there is no guarantee that if will be true.

  • The compiler returns this to me when trying to execute the code. java.lang.RuntimeException: Uncompilable source code - variable string might not have been initialized

  • I would need to see this in context. I’m finding it awful. But put yourself null resolve? I mean, have to do to meet design bad of others? :)

  • 1

    @Skywalker C# compiler also accuses this type of error. It’s a useful warning because if the programmer returned a variable that may never have been assigned anything, it could be a programming error (probably forgot to write a line of code that was intended to write); and if the programmer really wants to proceed with null in the case of non-attribution, the compiler requires it to explicitly state this intention.

Show 1 more comment

5

I do not believe that it is good practice to make explicit or not, even in cases of local scope in methods, where most of the time it is necessary to initialize.

The reason is to leave open the possibility of having to deal with the Exception most common in development, the NullPointerException.

To good practice that I know is always or whenever possible initialize to variable, be her type primitive or a object.

So not having a null even in case of attributes opitional, consequently avoiding the NullPointerException.

Ex:

public class Endereco {

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

   //getters e setters
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.