Method 4 is best.
if(foo != null && foo.bar()) {
someStuff();
}
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.
Method 4 is best.
if(foo != null && foo.bar()) {
someStuff();
}
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.
The last and the best one. i.e LOGICAL AND
if (foo != null && foo.bar()) {
etc...
}
Because in logical &&
it is not necessary to know what the right hand side is, the result must be false
Prefer to read :Java logical operator short-circuiting
Videos
If null is a reasonable input parameter for your method, fix the method. If not, fix the caller. "Reasonable" is a flexible term, so I propose the following test: How should the method hande a null input? If you find more than one possible answer, then null is not a reasonable input.
Don't use null, use Optional
As you've pointed out, one of the biggest problems with null in Java is that it can be used everywhere, or at least for all reference types.
It's impossible to tell that could be null and what couldn't be.
Java 8 introduces a much better pattern: Optional.
And example from Oracle:
String version = "UNKNOWN";
if(computer != null) {
Soundcard soundcard = computer.getSoundcard();
if(soundcard != null) {
USB usb = soundcard.getUSB();
if(usb != null) {
version = usb.getVersion();
}
}
}
If each of these may or may not return a successful value, you can change the APIs to Optionals:
String name = computer.flatMap(Computer::getSoundcard)
.flatMap(Soundcard::getUSB)
.map(USB::getVersion)
.orElse("UNKNOWN");
By explicitly encoding optionality in the type, your interfaces will be much better, and your code will be cleaner.
If you are not using Java 8, you can look at com.google.common.base.Optional in Google Guava.
A good explanation by the Guava team: https://github.com/google/guava/wiki/UsingAndAvoidingNullExplained
A more general explanation of disadvantages to null, with examples from several languages: https://www.lucidchart.com/techblog/2015/08/31/the-worst-mistake-of-computer-science/
@Nonnull, @Nullable
Java 8 adds these annotation to help code checking tools like IDEs catch problems. They're fairly limited in their effectiveness.
Check when it makes sense
Don't write 50% of your code checking null, particularly if there is nothing sensible your code can do with a null value.
On the other hand, if null could be used and mean something, make sure to use it.
Ultimately, you obviously can't remove null from Java. I strongly recommend substituting the Optional abstraction whenever possible, and checking null those other times that you can do something reasonable about it.
The dilemma
If a variable with null value gets used in your program causing a NullPointerException, this is clearly a situation in your program which you did not expect. You must ask yourself the question: "Did I not expect it because I didn't take into consideration the possibility of a null value or did I assume the value could never be null here?"
If the answer is the latter, the problem isn't because you didn't handle the null value. The problem happened earlier, and you're only seeing the consequence of that error on the particular line it's used. In this case, simply adding a if (variable != null) isn't going to cut it. You'll wind up skipping lines you were supposed to execute because the variable was null, and you'll ultimately hit a line further on where you again assumed it wouldn't be null.
When null should be used
As a general rule, return null only when "absent" is a possible return value. In other words, your data layer may search for a record with a specific id. If that record isn't found, you can either throw an exception or simply return null. You may do either, but I prefer not to throw exceptions in situations where the strong possibility exists. So you return null instead of a value.
The caller of this method, presumably written by you, knows the possibility exists that the record may not exist and checks for null accordingly. There is nothing wrong with this in this case, though you should handle this possibility as soon as possible as otherwise everywhere in your program you will need to deal with the possibility of a null value.
Conclusion
In other words, treat null as a legitimate value, but deal with it immediately rather than wait. Ideally in your program, you should ever only have to check if it is null once in your program and only in the place where such a null value is handled.
For every value you expect to be non-null, you need not add a check. If it is null, accept that there is an error in your program when it was instantiated. In essence, favor fail fast over fail safe.
Deciding whether or not null is a allowed as an object value is a decision that you must make consciously for your project.
You don't have to accept a language construct just because it exists; in fact, it is often better to enforce a strict rule against any nullvalues in the entire project. If you do this, you don't need checks; if a NullPointerException ever happens, that automatically means that there is a defect in your code, and it doesn't matter whether this is signalled by a NPE or by some other sanity check mechanism.
If you can't do this, for instance because you have to interoperate with other libraries that allow null, then you do have to check for it. Even then it makes sense to keep the areas of code where null is possible small if possible. The larger the project, the more sense it makes to define an entire "anti-corruption layer" with the only purpose of preserving stricter value guarantees than is possible elsewhere.
If that is needed, why JVM cannot the job by default.
It does! It checks if the value is null, and if not, throws a NullPointerException. In many cases this is the appropriate behaviour and you do not need to change it.
Normally it's easiest to simply declare variables or methods so that they never return a null. However, sometimes it's unavoidable, like in some existing methods in the API, and some self-created methods and variables need to have a null value set. Personally I recommend avoiding null values whenever possible--it's always best to declare a variable from the start, or have a method return, for example, a -1 instead of a null if a certain operation fails. In general though, if you know a variable or method may have a null value, you should do a null check at the beginning just to be on the safe side.
Hope this helps, and I wish you the best of luck!
It is a good idea to check for null explicitly because:
- You can catch the error earlier.
- You can provide a more descriptive error message.
If you get a NullPointerException you might not be able to work out exactly which variable was null. Even if you have the line number where the exception was thrown, there might still be more than one variable on that line.
It's particularly important to put these checks in your public interface. This is because when your user provides an incorrect parameter they should get an IllegalArgumentException telling them that they made an error. If they just get back a NullPointerException they can't tell if they provided an incorrect parameter, or if there is just a bug in your code.
Here are some of the best practices in the order of importance:
- Don't return a null if you can help it. For example, if your method returns a collection, return an empty collection rather than a null. In some instances the Null Object pattern can be of help. But you have to be careful to only use it where the NullObject can offer a reasonable default behavior without an additional if-check.
- Check for nulls if your code can offer a reasonable handling of null cases. If you simply throw another exception upon detecting a null, there is little value in handling the null explicitly.
- Document all instances of a function returning nulls in the function's javadoc. (unfortunately, you can't really rely on the javadoc, but it help in maintaining discipline).
I'm coming back to Java after almost 10 years away programming largely in Haskell. I'm wondering how folks are checking their null-safety. Do folks use CheckerFramework, JSpecify, NullAway, or what?