Avoiding "!= null" comparison in Java

Asked

Viewed 15,299 times

15

I work with Java and for countless times I have to take 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 difficult 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 becomes:

if (pessoa!=null) {
    System.out.println("Nome: " + pessoa.getNome());
}
  • Interesting, both question and answer are translations from the source you listed.

  • Yes. What did you mean?

  • It was just a statement, I don’t see anything wrong. In stackoverflow in English, one of the requirements is that the author asks a question about a concrete problem he is encountering, not theoretical. I don’t know what the recommendations for the Portuguese version are, but I think it would be more sincere if you put a warning at the top saying that the question and answer originally appeared in the English version, with a link to it. As it stands, it seems that the question and answer are your original, with "font" in the English version. Source, in this case, being "copy" (usually, "source" is only a reference).

  • I understand your point. I also thought this was incorrect/strange at first, but there is a post in the goal that quotes exactly this: We support the rewriting of Stack Overflow questions or answers, provided they benefit your community. Always keep in mind, however, that automated or poorly written translations are not allowed. This is not the stackoverflow.com. By the way, I didn’t just translate, I made my point on that. This was a real problem that I have faced in the past and that question/answer has already helped me.

  • Ok, I also think this question/answer benefits the community, but if I were the author of the question/answer of the originals, I would have the feeling that it is a copy without proper attribution of the authorship, however much I have one or another original element :-)

  • What would the author of this question or answer in the SO.com then find: Why processing an ordered list is faster than an unordered list? ? :-)

  • I hadn’t seen it, but I’d make the same comment I made here...

  • 1

    By the way, at the bottom of the question he put: "Based on a famous OS question". That’s enough attribution, I imagine.

  • Original link: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java

Show 4 more comments

3 answers

14


Which code style to use?

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

  • Contract programming is something more difficult to find out. It preaches that one should see what the method expects, what the documentation says to use and follow. Developer problem if you don’t follow these rules. Errors will happen but it doesn’t matter, it didn’t send the data right. How does this affect the code? You would not need to validate the received attributes and simply let the error crash. The problem with this approach is the many Runtime errors that will appear and also the constant need for detailed and up-to-date documentation.
  • Already the defensive programming preaches that you should validate everything that is important for the called method. Validate from the simple attributes (String, int, etc) as objects of your model (Home, Car, etc). The disadvantage of this is that you will always have a if more in your code for validation.

What can I do to validate?

You can use various techniques to validate an attribute:

  • Use libraries that decrease code. Apachecommons, for example, has several classes that facilitate validation. I can cite the StringUtils.isBlank(texto) to validate whether the text is empty or not. And the interesting thing is that to facilitate the reading of the code, they created the method isNotBlank(texto) which is denial.
  • Use JSR 303: Bean Validation. This is the data validation specification. Just note with a @NotNull and ready. Take a look at the Hibernate Validator.
  • Make an IF in the nail. This is a very simple solution, but as already said it leaves the larger code. The best thing would be to isolate this code in a separate method.
  • Utilize assert. This I do not recommend and to tell you the truth, nobody recommends the use of the assert in production. It kills the thread that invoked the method.

Completion

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

  • A proof that this is not the.com :-). In the end it is the community that decides what is good for here or not. But one thing intrigued me, why do not you recommend asserts? I will research on this, but it is the first time I see someone desrecommending.

  • Precisely because of your concept. It is not advisable to perform a Try/catch on an assert (http://www.coderanch.com/t/396087/java/assert-statements-catch-blocks). The concept of assert is, gave problem and the thing was ugly. So much so that to activate an assert parameter in the JVM it is necessary -ea for example. In google it’s easy to find references that say assert should not be used in production. http://stackoverflow.com/questions/4347164/appropriate-use-of-assert

4

Complementing the above answers, I have one more suggestion.

It runs a long way from what you normally see in Java, but it’s very interesting.

The API Google Guava, which is another one of those penknives you have available to help you, has a part oriented to treating nulls.

They themselves exemplify in documentation but I’ll leave some examples here to clarify the answer.

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

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

What happened there? You have a class Optional<T> that may or may not have a value, only that it forces you to treat that value on time, because if you invoke get() without a value inside, a IllegalStateException, just to not exist null 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 you perform these treatments away from the business rule. Once you receive them from the user, or at the time you return them from the database, so you don’t worry about it in the more complex parts.

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

"Null sucks." - Doug Lea

3

This is a problem that developers without much experience often face: they either don’t know or don’t trust the contract they are participating in and the defensive end up exaggerating in null’s verification. 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 short, there are two cases that require null’s verification:

1) When null is not a valid response in terms of contract:

In this case, use the resource Assertionerror or just let the exception occur, use the information generated by error or exception to debug gave code and understand why the unwanted condition happened, so fix your logic to avoid this condition. Do all kinds of possible tests, the sooner the error or the exception occurs better, you will not want to discover a bug after you have released your program.

assertion is a feature that has been added to Java 1.4 but is not yet so practiced by programmers. It is great to find bugs because you can do tests to make sure you are getting the expected result at certain points of the program.

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

Correct, however with assertions you test in a much more practical way because you do not need to write a whole code handling and display the error message. In addition the assert is not enabled by default, so you can enable it while debugging your program and when distributing it asserts will normally be disabled. Using a logic with if you should remember to erase the error debugging code before distributing your program so as not to risk 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 one AssertionError is launched. If an object has been specified in the second parameter the method toString() of objeto will be added to the error information released 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 short:

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 your objects and attributes, so they never return null, nor does the object method return emptiness That avoids the dreaded NullPointerException.

You might want to take a look at 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 Animal class object like null initialize it as NullAnimal

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

Browser other questions tagged

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