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
Update: Pattern matching for switch arrived in Java 21.
tl;dr
switch expressions != pattern matching with switch
You are mixing up the relatively new feature of switch expressions with the still-not-released feature of pattern matching with switch.
The switch feature in Java has been evolving through 3 phases, two completed:
-
switchstatement (original feature in Java 1) -
switchexpression (Java 14+) - Pattern matching for
switch, includingcase null(previewed in Java 17, 18, 19, & 20)
Do not conflate switch expressions with pattern matching
Classic switch
Understand that historically, the Java switch statement has been hostile to null checks. See this Question, How to use null in switch. As shown there, code such as this:
switch ( i ) {
case null:
doSomething0();
break;
}
… was not possible.
switch expressions
Fast forward to Java 14, when switch expressions was added to Java. A switch can return a value. See JEP 361: Switch Expressions.
The switch expressions feature provides the syntax seen in your first code example:
return switch ( testEnum ) {
case FOO -> newFoo();
case BAR -> newBar();
}
But read the JEP. No mention of null — « crickets ».
Pattern matching for switch
Fast forward further, to JEP 406: Pattern Matching for switch (Preview). Note that this is a preview feature in Java 17, not a final, officially released feature. (To understand how preview features work, read JEP 12: Preview Features.)
In that JEP 406, notice its second goal: Allow the historical null-hostility of switch to be relaxed when desired.
Now search that page for “null” — 73 hits! That page explains the former policy of the Java language:
Traditionally,
switchstatements and expressions throwNullPointerExceptionif the selector expression evaluates tonull…
Notice the mention of statements, the original switch syntax, and additionally expressions, the new syntax used in your code. In both cases, null check was forbidden.
That page goes on to explain the changes that motivate the inclusion of support for null checks. Read the JEP for well-written details.
The upshot is that you can use case null in a switch in Java 17 — but only if you go out of your way to enable the preview feature.
Arrived in Java 21
This feature arrived in Java 21. See JEP 441: Pattern Matching for switch.
Example
Let's try this code example. Notice how we use plain old syntax here, without the ->. The arrow operator is not related to our discussion here.
String x = null;
switch ( x )
{
case "starburst":
System.out.println( "Is starburst." );
break;
case null:
System.out.println( "Whoops, null." );
break;
default:
System.out.println( "Some other value found." );
break;
}
This command line works for me:
$ javac -version
javac 17.0.3
$ javac -source 17 -Xlint:preview --enable-preview org/kablambda/Main.java
org/kablambda/Main.java:10: warning: [preview] null in switch cases is a preview feature and may be removed in a future release.
case null -> "c";
^
1 warning
Your solution is very smart. The problem I see is the fact that you don't know why you got a null? Was it because the house had no rooms? Was it becuase the town had no houses? Was it because the country had no towns? Was it because there was a null in the 0 position of the collection because of an error even when there are houses in positions 1 and greater?
If you make extensibe use of the NonPE class, you will have serious debugging problems. I think it is better to know where exactly the chain is broken than to silently get a null that could be hiding a deeper error.
Also this violates the Law of Demeter: country.getTown().getHouses().get(0).getLivingRoom(). More often than not, violating some good principle makes you have to implement unorthodox solutions to solve the problem caused by violating such principle.
My recommendation is that you use it with caution and try solve the design flaw that makes you have to incur in the train wreck antipattern (so you don't have to use NonPE everywhere). Otherwise you may have bugs that will be hard to detect.
The idea is fine, really good in fact. Since Java 8 the Optional types exist, a detailed explanation can be found at Java Optional type. A example with what you posted is
Optional.ofNullable(country)
.map(Country::getTown)
.map(Town::Houses);
And further on.
I'm 4 y experienced Java dev but still it's unclear how and when to check nullity sometimes and it happened today. Let's say there is a table called students and it has column called `last_name` which is not null.
create table students (
last_name varchar(255) not null
)You have written validation code to ensure all required column is appeared while inserting new record and there is a method that needs last_name of students. The parameter of this method may or may not come from DB directly(It could be mapped as DTO). In this case do you check nullity of `last_name` even though you wrote validation code? Or just skip the null check since it has not null constraint?
I know this depends on where and how this method is used and i skipped the null check because i think this method is not going to be used as general purpose method only in one class scope.
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?
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.
To put this another way, there are two instances where null checking comes up:
Where null is a valid response in terms of the contract; and
Where it isn't a valid response.
(2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)
"Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.
public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}
It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.
Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();
Generally throwing a specific exception like NullPointerException when a value is null but shouldn't be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.
(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.
If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.
With non-collections it might be harder. Consider this as an example: if you have these interfaces:
public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.
An alternative solution is to never return null and instead use the Null Object pattern:
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
Compare:
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
to
ParserFactory.getParser().findAction(someInput).doSomething();
which is a much better design because it leads to more concise code.
That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.
try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}
Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.
public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}
If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.
Basically, you've got @Nullable and @NotNull.
You can use in method and parameters, like this:
@NotNull public static String helloWorld() {
return "Hello World";
}
or
@Nullable public static String helloWorld() {
return "Hello World";
}
The second example won't compile (in IntelliJ IDEA).
When you use the first helloWorld() function in another piece of code:
public static void main(String[] args)
{
String result = helloWorld();
if(result != null) {
System.out.println(result);
}
}
Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.
Using parameter
void someMethod(@NotNull someParameter) { }
if you write something like:
someMethod(null);
This won't compile.
Last example using @Nullable
@Nullable iWantToDestroyEverything() { return null; }
Doing this
iWantToDestroyEverything().something();
And you can be sure that this won't happen. :)
It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.
In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.
See blog post More flexible and configurable @Nullable/@NotNull annotations.
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.