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 if
s, 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 assert
s 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?
Interesting, both question and answer are translations from the source you listed.
– jpkrohling
Yes. What did you mean?
– Math
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).
– jpkrohling
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.
– Math
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 :-)
– jpkrohling
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? ? :-)
– Math
I hadn’t seen it, but I’d make the same comment I made here...
– jpkrohling
By the way, at the bottom of the question he put: "Based on a famous OS question". That’s enough attribution, I imagine.
– jpkrohling
Original link: http://stackoverflow.com/questions/271526/avoiding-null-statements-in-java
– user622