Avoiding comparison "! = null" in Java

15

I work with Java and for countless times I have to do a test object != null on the object before accessing it to avoid NullPointerException

However, I think this practice ends up making the code very ugly, dirty and hard to read.

Is there any alternative to avoid this comparison every time I want to access the method of an object?

For example:

System.out.println("Nome: " + pessoa.getNome());

To stay safe it becomes:

if (pessoa!=null) {
    System.out.println("Nome: " + pessoa.getNome());
}
    
asked by anonymous 06.02.2014 / 11:38

3 answers

13

What style of code to use?

There are two types of programming that we can use: contract or defense.

  • Schedule by contract is something harder to find out there. She preaches that person should see what the method expects, what the documentation says to use and follow. Developer issue if you do not follow these rules. Errors will happen but it does not matter, he did not send the data right. How does this affect the code? You would not need to validate the received attributes and simply let the error pop. The problem with this approach is the various runtime errors that will appear and also the constant need for detailed and up-to-date documentation.
  • Defensive programming already preaches that you should validate everything that is important to the called method. Validate from simple attributes ( String , int , etc) as objects of your model (Home, Car, etc). The downside of this is that you will always have%% more in your code for validation.

What can I do to validate?

You can use several techniques to validate an attribute:

  • Use libraries that lower the code. ApacheCommons, for example, has several classes that make validation easier. I can cite if to validate whether the text is empty or not. And the interesting thing is that to make it easier to read the code, they created the StringUtils.isBlank(texto) method, which is the negation.
  • Use JSR 303: Bean Validation. It is the data validation specification. Just score with a isNotBlank(texto) and that's it. Take a look at Hibernate Validator.
  • Make an IF on the nail. This is a very simple solution, but as I said, it leaves the code bigger. The best thing would be to isolate this code in a separate method.
  • Use assert. This one I do not recommend and to tell you the truth, no one recommends using assert in production. It kills the thread that invoked the method.

Conclusion

For this type of situation there is no perfect solution, but there are alternatives that help in developing a cleaner code.

    
06.02.2014 / 12:17
4

Complementing the above answers, I have one more suggestion.

It even runs away from what you normally see in Java, but it's very interesting.

The Google Guava API is one more of these pocketknives that you have available to help you, has a null-oriented part.

They themselves exemplify the documentation but I will leave some examples here to clarify the answer.

/ p>

First example of how to completely remove null from your code:

Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // retorna true
possible.get();       // retorna 5

What happened there? You have a Optional<T> class that may or may not have a value, but it forces you to treat that value on time, because if you invoke get() without a value therein, a IllegalStateException is thrown, just not null exists nowhere.

If you want a default value it is also possible:

possible.or(0); // retorna o valor se existir, se não houver nada, retorna 0

The idea is for you to perform these treatments far from the business rule. Once you get them from the user, or the moment you return them from the database, so you do not worry about it in the more complex parts.

If you click the link above you will see many more classes, examples, and utilities.

  

"Null sucks." - Doug Lea

    
06.02.2014 / 12:30
3

This is a problem that developers without much experience often face: they either do not know or do not trust the contract they are participating in and defensive end up exaggerating in checking by null's. Additionally, when they write their own code, they have the habit of returning null's to indicate something, and this ends up generating the need to check for null's by the method that tried to invoke the object.

In summary, there are two cases that require verification by null's:

1) When null is not a valid contract response:

In this case, use the AssertionError feature or just leave the exception occurs, use the information generated by error or exception to debug the code and understand why the unwanted condition happened, then fix your logic to avoid this condition. Make all sorts of tests possible, the sooner the error or exception occurs the better, you will not want to discover a bug once you've launched your program.

assertion is a feature that has been added to Java 1.4 but is still not as widely practiced by programmers. It's great to find bugs because you can do tests to make sure you're getting the expected result at certain points in the program.

"- But I can do these tests using if s, correct?"

Correct, however with assertions you test in a much more practical way as you do not need to write a whole code to manipulate and display the error message. Furthermore, assert is not enabled by default, so you can enable it while debugging your program, and when you distribute it, the assert s is normally disabled. Using a logic with if you should remember to erase the debugging code before distributing your program so that you do not run the risk of displaying a message to the user that should never have been displayed.

Syntax:

assert <condição>

or

assert <condição> : <objeto>

If the condition fails a AssertionError is thrown. If an object has been indicated in the second parameter the toString() method of objeto will be added to the error information posted by AssertionError .

Example:

public Pessoa obterPessoa(int id) {
    Pessoa resultado = null;
    if (id > 50) {
        resultado = datasource.getPessoa(id);
    } else {
        resultado = new Pessoa(id);
    }
    assert resultado != null : "pessoa nula no método obterPessoa()";

    return resultado;
}

In summary:

  

Know your contract, debug it and trust it.

2) If null is a valid contract response:

In this case there is not much choice, you have to test the object before using it.

Or if you want to improve your code, you can change it and initialize its objects and their attributes, so that they never return null , nor that the object method returns empty this already avoids the dreaded NullPointerException .

You may want to take a look at the Null Object Pattern

Example:

public interface Animal {
    public void makeSound();
}

public class Dog implements Animal {
    public void makeSound() {
        System.out.println("woof!");
    }
}

public class NullAnimal implements Animal {
    public void makeSound() {
    }
}

Instead of initializing an object of class Animal as null initialize it as NullAnimal

Source (s): Avoiding "! = null" statements in Java?

    
06.02.2014 / 11:38