Avoiding NullPointerException in Java

Created 07.11.2008 08:31
Viewed 1.31M times
4187 votes

I use object != null a lot to avoid NullPointerException.

What is an alternative to:

if (someobject != null) {
    someobject.doCalc();
}
8
Comments
@Shervin Encouraging nulls makes the code less understandable and less reliable. by Tom Hawtin - tackline, 02.08.2010 09:17
Not using null is superior to most other suggestions here. Throw exceptions, don't return or allow nulls. BTW - 'assert' keyword is useless, because it's disabled by default. Use an always-enabled failure mechanism by ianpojman, 08.06.2012 19:40
You can create class that will check for null values or null object. That will help you improving reuse-ability.. stackoverflow.com/a/16833309/1490962 by Bhushankumar Lilapara, 30.05.2013 10:15
use Lombok, you got @NotNull by wener, 09.10.2013 18:21
Isn't there are Design Pattern that speaks about making a null-object? So when instantiating a new object, you always use this null object (same super class, same [but empty] methods) and later on you set the object to the full object when you need it. You might want to check out a similar question: stackoverflow.com/questions/9162371/… and this info about the Null Object Pattern: en.wikipedia.org/wiki/Null_Object_pattern by BlueCacti, 13.08.2014 07:37
Nulls should be avoided in high-level code. Tony Hoare, who invented null references, calls them "a billion-dollar mistake". Take a look here for some ideas. by Andrii Polunin, 04.04.2016 13:05
Seems to be in Java 8: static Objects.isNull(Object o) docs.oracle.com/javase/8/docs/api/java/util/Objects.html by Robert R Evans, 23.06.2016 17:02
How about wrapping the object with Optional . Use optional where ever you see possibility of nulls by Abhishek kapoor, 28.02.2017 05:13
Show remaining 3 comments
Answers 50
0
2735

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:

  1. Where null is a valid response in terms of the contract; and

  2. Where it isn't a valid response.

(2) is easy. Either use assert statements (assertions) or allow failure (for example, NullPointerException). Assertions are a highly-underused Java feature that was added in 1.4. The syntax is:

assert <condition>

or

assert <condition> : <object>

where <condition> is a boolean expression and <object> is an object whose toString() method's output will be included in the error.

An assert statement throws an Error (AssertionError) if the condition is not true. By default, Java ignores assertions. You can enable assertions by passing the option -ea to the JVM. You can enable and disable assertions for individual classes and packages. This means that you can validate code with the assertions while developing and testing, and disable them in a production environment, although my testing has shown next to no performance impact from assertions.

Not using assertions in this case is OK because the code will just fail, which is what will happen if you use assertions. The only difference is that with assertions it might happen sooner, in a more-meaningful way and possibly with extra information, which may help you to figure out why it happened if you weren't expecting it.

(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);
        }
    }
}
07.11.2008 12:06
16
671

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.

05.03.2010 10:31
Comments
@NotNull, @Nullable and other nullness annotations are part of JSR 305. You can also use them to detect potential problems with tools like FindBugs. by Jacek S, 08.05.2010 16:33
I find it strangely annoying that the @NotNull & @Nullable interfaces live in the package com.sun.istack.internal. (I guess I associate com.sun with warnings about using a proprietary API.) by Jonik, 30.06.2011 23:33
code portability goes null with jetbrains.I would think twice(square) before tying down to ide level.Like Jacek S said they are part of JSR any way which I thought was JSR303 by the way. by Java Ka Baby, 08.09.2011 09:39
Why doesn't the 2nd one compile though? by Mechanical snail, 17.08.2012 07:02
I really don't think that using a custom compiler is a viable solution to this problem. by Shivan Dragon, 19.08.2012 08:24
The good thing about annotations, which @NotNull and @Nullable are is that they nicely degrade when the source code is built by a system that doesn't understand them. So, in effect, the argument that the code is not portable may be invalid - if you use a system that supports and understands these annotations, you get the added benefit of stricter error checking, otherwise you get less of it but your code should still build fine, and the quality of your running program is THE SAME, because these annotations were not enforced at runtime anyway. Besides, all compilers are custom ;-) by amn, 20.03.2013 09:49
in your example you call helloWorld twice. This is terrible. you have no idea what could be the consequences ! by njzk2, 03.03.2014 14:26
@Mechanicalsnail becuase it only ever returns "hello world", and can never return null. by NimChimpsky, 15.05.2014 12:32
@JacekS Just for information - for Android development, As of version 19.1 of the Android support library, @NotNull and @Nullable annotation support has been added. So basically all Android developer can take advantage of it. It won't be IDE specific anymore. More information regarding support annotations here - tools.android.com/tech-docs/support-annotations by shaktiman_droid, 26.09.2014 17:42
Arguments against @Nullable/@NotNull for "compatibility" are missing the point. They are only there to help tools (from a static analysis) ensure that these basic contracts are met - they do not replace proper null handling, when such is appropriate per the contract (or possible per the input source). While it would be awesome if Java and C# (and the run-times) actually supported not-null reference types in the Type System, using better static analysis tooling (and explicit annotated contracts) goes a long way to reduce the 100 trillion dollar mistake that is Algo, is Java, is C# .. by user2864740, 04.02.2015 16:05
Netbeans also has support for @NotNull and @Nullable. by DuncanKinnear, 18.06.2015 22:51
It's worth noting that TYPE_USE annotations (since Java 8) let you treat null annotations as an integral part of the type system, including in particular generics. This means that conceptually all contract violations can be detected by the compiler. Eclipse supports this since Java 8 was released, see help.eclipse.org/topic/org.eclipse.jdt.doc.user/tasks/… by Stephan Herrmann, 28.07.2015 19:25
What error message does the second example give (in IntelliJ IDEA)? by mwfearnley, 13.06.2017 14:28
This should now be the primary answer, I believe the accepted answer was accepted before these annotations were available. I wonder if there is a way to get it promoted to the top at least... by Bill K, 17.04.2018 16:59
@mwfearnley I believe the comment on the second answer was incorrect, Nullable is more of a warning to the developer and I don't think the compiler proves that it can be null (Since an overridden method could return null). What it DOES mean is that it can't be passed to a NotNull without being protected by a null check. by Bill K, 17.04.2018 17:02
By the way, the implementations of the checkers are not all consistent! Eclipse's checker is a good deal better than IntelliJ's (although I've been using IntelliJ's, it's definitely better than nothing). Eclipses has much better handling of un-annotated variables. stackoverflow.com/questions/48349393/… by Bill K, 17.04.2018 17:04
Show remaining 11 comments
12
336

If null-values are not allowed

If your method is called externally, start with something like this:

public void method(Object object) {
  if (object == null) {
    throw new IllegalArgumentException("...");
  }

Then, in the rest of that method, you'll know that object is not null.

If it is an internal method (not part of an API), just document that it cannot be null, and that's it.

Example:

public String getFirst3Chars(String text) {
  return text.subString(0, 3);
}

However, if your method just passes the value on, and the next method passes it on etc. it could get problematic. In that case you may want to check the argument as above.

If null is allowed

This really depends. If find that I often do something like this:

if (object == null) {
  // something
} else {
  // something else
}

So I branch, and do two completely different things. There is no ugly code snippet, because I really need to do two different things depending on the data. For example, should I work on the input, or should I calculate a good default value?


It's actually rare for me to use the idiom "if (object != null && ...".

It may be easier to give you examples, if you show examples of where you typically use the idiom.

07.11.2008 09:27
Comments
What's the point in throwing IllegalArgumentException? I think NullPointerException would be clearer, and that would also be thrown if you don't do the null-check yourself. I'd either use assert or nothing at all. by Axel, 09.08.2011 16:47
It's unlikely that every other value than null is acceptable. You could have IllegalArgumentException, OutOfRageException etc etc. Sometimes this makes sense. Other times you end up creating a lot of exception classes that doesn't add any value, then you just use IllegalArgumentException. It doesn't makes sense to have one exception for null-input, and another one for everything else. by myplacedk, 15.08.2011 12:26
Yes, I agree to fail-fast-principle, but in the example given above, the value is not passed on, but is the object on which a method shall be called. So it fails equallys fast, and adding a null check just to throw an exception that would be thrown anyway at the same time and place doesn't seem to make debugging any easier. by Axel, 22.08.2011 11:20
I agree with @Axel in that IllegalArgumentException implies (as I use it anyway) that a precondition for the argument does not hold as it pertains to a constraint on the parameter. A null parameter is usually just "a general error in programming" and not an application/API specific constraint. To maintain a defensive fail-fast strategy, there's nothing stopping anyone for checking for a null and throwing a NullPointerException... which exactly conveys what happened, namely, "you didn't program it right" :) by charstar, 03.12.2011 09:54
"A null parameter is usually just "a general error in programming" and not an application/API specific constraint." Naive. You can use this as a security hole to DoS or attempt to gain stacktrace info (if such information is not supressed). osvdb.org/show/osvdb/67379 If your API is public and you don't explicitly define the boundaries you accept--both through API docs and whatever tools you can use to ensure validity of the contract-- the caller's free to do whatever they want. You are the one who didn't program right then, not the caller. by Visionary Software Solutions, 07.09.2012 18:23
A security hole? The JDK is full of code like this. If you don't want the user to see stacktraces, then just disable them. No one implied that the behaviour is not documented. MySQL is written in C where dereferencing null pointers is undefined behaviour, nothing like throwing an exception. by fgb, 08.04.2013 00:39
throw new IllegalArgumentException("object==null") by Thorbjørn Ravn Andersen, 20.04.2013 23:35
@myplacedk I think it does make sense to have a different exception for null values passed in that from improper values passed in. The two are usually results of different types of programming errors. Null values usually arise from some required computation not happening, while other problems usually arise from required computations being incorrect. by corsiKa, 13.06.2013 23:16
@Axel the whole point of using anything other than RuntimeException is the descriptiveness of the Exception. Why IllegalArgumentException over NullPointerException? Because when you are debugging an exception caused by this, the IllegalArgumentException is abundantly more obvious, especially when you put a message on it. This especially applies to enterprise applications when NullPointerExceptions creep up (yes, these happen in enterprise applications). In this same example, the programmer may not have control over whether or not assertions get processed by the JVM. by Michael Plautz, 13.05.2015 02:01
1/2 I have to agree that a IllegalArgumentException is better than a plain-vanilla NPE for these type of situations. I see a NPE as an indication that somewhere in the code, something unsafely de-referenced an expression that happened to be null (assuming all known and declared preconditions and invariants were met). An illegal argument exception OTH tells me a well-known precondition or invariant was not met. by luis.espinal, 12.08.2016 17:28
2/2 - That is, a NPE tells me there is a yet-undocumented null bug within the method (or within the methods it calls) or that there is a null precondition that we have not coded for. An illegal argument exception tells there is a bug outside of this method lying somewhere along the call chain that leads to the current method. Sticking to this pattern (within reason obviously), it does lead to faster root-cause analysis of errors (specially the nasty, intertwined ones.) by luis.espinal, 12.08.2016 17:33
Throwing NullPointerException is the Java convention. See e.g. Objects.requireNonNull which is "primarily for doing parameter validation in methods and constructors" and throws NullPointerException. There is also simply the doc for NullPointerException which states that "applications should throw instances of this class to indicate other illegal uses of the null object". by Radiodef, 07.05.2017 21:51
Show remaining 7 comments
9
247

Wow, I almost hate to add another answer when we have 57 different ways to recommend the NullObject pattern, but I think that some people interested in this question may like to know that there is a proposal on the table for Java 7 to add "null-safe handling"—a streamlined syntax for if-not-equal-null logic.

The example given by Alex Miller looks like this:

public String getPostcode(Person person) {  
  return person?.getAddress()?.getPostcode();  
}  

The ?. means only de-reference the left identifier if it is not null, otherwise evaluate the remainder of the expression as null. Some people, like Java Posse member Dick Wall and the voters at Devoxx really love this proposal, but there is opposition too, on the grounds that it will actually encourage more use of null as a sentinel value.


Update: An official proposal for a null-safe operator in Java 7 has been submitted under Project Coin. The syntax is a little different than the example above, but it's the same notion.


Update: The null-safe operator proposal didn't make it into Project Coin. So, you won't be seeing this syntax in Java 7.

17.01.2009 05:08
Comments
I think this is wrong. There should be a way to specify that a given variable is ALWAYS non-null. by Thorbjørn Ravn Andersen, 26.05.2009 11:54
Update: the proposal will not make Java7. See blogs.sun.com/darcy/entry/project_coin_final_five . by Boris Terzic, 29.08.2009 18:56
But on the same page, see the link to types.cs.washington.edu/jsr308 for info about using the Checker framework to add the @Nullable and @NonNull type annotations in Java 7. by Ogre Psalm33, 10.12.2010 13:00
Interesting idea but the choice of syntax is absurd; I don't want a codebase full of question marks pinned into every joint. by Rob, 16.05.2012 11:51
This operator exists in Groovy, so those who want to use it still have that as an option. by Muhd, 15.02.2013 22:53
Optional was added to Java8 by sprinter, 24.12.2014 03:29
This is the most ingenious idea I've seen. It should be added to every sensible language of the C syntax. I'd rather "pin question marks" everywhere than scroll through screenful of lines or dodge "guard clauses" all day. by Victor, 01.10.2015 20:57
Tony Hoare apologised for inventing null. But an even bigger mistake is to pick a strategy, to stick to it for over 20 years until billions lines of code are written, to then finally change your mind. This .? was like a last chance to keep java "clean". It's a very simple syntactical solution. But instead they prefer to throw in a handful of different @Nullable and Option classes, empty collections, empty objects. The goal was to make nullability easier. But instead they added many layers of complexity. In the end, this will split the java community and will drive it to distruction. by bvdb, 23.04.2016 14:12
Kotlin has the null safe call operators, too. kotlinlang.org/docs/reference/null-safety.html#safe-calls by IceArdor, 12.05.2017 08:33
Show remaining 4 comments
7
204

If undefined values are not permitted:

You might configure your IDE to warn you about potential null dereferencing. E.g. in Eclipse, see Preferences > Java > Compiler > Errors/Warnings/Null analysis.

If undefined values are permitted:

If you want to define a new API where undefined values make sense, use the Option Pattern (may be familiar from functional languages). It has the following advantages:

  • It is stated explicitly in the API whether an input or output exists or not.
  • The compiler forces you to handle the "undefined" case.
  • Option is a monad, so there is no need for verbose null checking, just use map/foreach/getOrElse or a similar combinator to safely use the value (example).

Java 8 has a built-in Optional class (recommended); for earlier versions, there are library alternatives, for example Guava's Optional or FunctionalJava's Option. But like many functional-style patterns, using Option in Java (even 8) results in quite some boilerplate, which you can reduce using a less verbose JVM language, e.g. Scala or Xtend.

If you have to deal with an API which might return nulls, you can't do much in Java. Xtend and Groovy have the Elvis operator ?: and the null-safe dereference operator ?., but note that this returns null in case of a null reference, so it just "defers" the proper handling of null.

14.01.2010 13:45
Comments
Indeed, the Option pattern is awesome. Some Java equivalents exist. Guava contains a limited version of this called Optional which leaves out most of the functional stuff. In Haskell, this pattern is called Maybe. by Ben Hardy, 20.05.2011 18:31
@Luca Molteni: You're absolutely right, I already commented on the post to request expanding it. :) by thSoft, 11.09.2011 20:59
An Optional class will be available in Java 8 by Pierre Henry, 25.04.2013 14:59
...and it doesn't (yet) have map nor flatMap: download.java.net/jdk8/docs/api/java/util/Optional.html by thSoft, 25.04.2013 15:28
The Optional pattern doesn't solve anything; instead of one potentially null object, now you have two. by Boann, 04.11.2013 04:15
Also, look at Functional Guava Extensions (fugue). This library also has its own Option. by ZhekaKozlov, 10.12.2013 05:07
Guava's Optional is not good in this case as transform throws an NPE when the function returns null. by Olivier Grégoire, 01.03.2016 16:48
Show remaining 2 comments
5
199

Only for this situation -

Not checking if a variable is null before invoking an equals method (a string compare example below):

if ( foo.equals("bar") ) {
 // ...
}

will result in a NullPointerException if foo doesn't exist.

You can avoid that if you compare your Strings like this:

if ( "bar".equals(foo) ) {
 // ...
}
09.11.2008 12:24
Comments
I agree - only in that situation. I can't stand programmers that have taken this to the next unnecessary level and write if (null != myVar)... just looks ugly to me and serves no purpose! by Alex Worden, 23.05.2011 18:14
This is a particular example, probably the most used, of a general good practice: if you know it, always do <object that you know that is not null>.equals(<object that might be null>);. It works for other methods other than equals if you know the contract and those methods can handle null parameters. by Stef, 23.09.2011 01:20
This is the first example I have seen of Yoda Conditions that actually makes sense by Erin Drummond, 30.09.2013 19:37
NullPointerExceptions are thrown for a reason. They are thrown because an object is null where it shouldn't be. It is the programmers job to FIX this, not HIDE the problem. by Oliver Watkins, 12.05.2014 07:49
This only hides the problem. What if you are using foo later on? If a variable shouldn't be null, but is...your app needs to get a NPE so you as the developer can actually fix the underlying reason. by Arnab Datta, 26.11.2015 08:57
7
173

With Java 8 comes the new java.util.Optional class that arguably solves some of the problem. One can at least say that it improves the readability of the code, and in the case of public APIs make the API's contract clearer to the client developer.

They work like that:

An optional object for a given type (Fruit) is created as the return type of a method. It can be empty or contain a Fruit object:

public static Optional<Fruit> find(String name, List<Fruit> fruits) {
   for (Fruit fruit : fruits) {
      if (fruit.getName().equals(name)) {
         return Optional.of(fruit);
      }
   }
   return Optional.empty();
}

Now look at this code where we search a list of Fruit (fruits) for a given Fruit instance:

Optional<Fruit> found = find("lemon", fruits);
if (found.isPresent()) {
   Fruit fruit = found.get();
   String name = fruit.getName();
}

You can use the map() operator to perform a computation on--or extract a value from--an optional object. orElse() lets you provide a fallback for missing values.

String nameOrNull = find("lemon", fruits)
    .map(f -> f.getName())
    .orElse("empty-name");

Of course, the check for null/empty value is still necessary, but at least the developer is conscious that the value might be empty and the risk of forgetting to check is limited.

In an API built from scratch using Optional whenever a return value might be empty, and returning a plain object only when it cannot be null (convention), the client code might abandon null checks on simple object return values...

Of course Optional could also be used as a method argument, perhaps a better way to indicate optional arguments than 5 or 10 overloading methods in some cases.

Optional offers other convenient methods, such as orElse that allow the use of a default value, and ifPresent that works with lambda expressions.

I invite you to read this article (my main source for writing this answer) in which the NullPointerException (and in general null pointer) problematic as well as the (partial) solution brought by Optional are well explained: Java Optional Objects.

25.04.2013 15:22
Comments
Google's guava has an optional implimention for Java 6+. by Bradley Gottfried, 27.05.2013 17:30
It's very important to emphasise that using Optional only with ifPresent() does not add much value above normal null checking. It's core value is that it is a monad that can be used in function chains of map/flapMap, which achieves results similar to the Elvis operator in Groovy mentioned elsewhere. Even without this usage, though, I find the orElse/orElseThrow syntax also very useful. by Cornel Masson, 09.10.2014 14:57
This blog has a good entry on Optional winterbe.com/posts/2015/03/15/avoid-null-checks-in-java by JohnC, 09.12.2015 00:05
I really never understood why people are so happy with this boilerplate code dzone.com/articles/java-8-elvis-operator by Mike, 23.02.2018 22:10
Why people have tendency to do this if(optional.isPresent()){ optional.get(); } instead of optional.ifPresent(o -> { ...}) by Satyendra Kumar, 07.03.2018 15:06
So, other than the API contractual hints, it's really just about catering to functional programmers who enjoy chaining methods endlessly. by crush, 09.08.2018 17:39
I know this post is old, but above example is a wrong use of Java 8's features imho. Do not combine imperative code with optionals like that. When having a fruit list + a name to search for, use the Streaming API: fruits.stream().filter(f -> name.equals(f.getName()).findFirst().map(Fruit::getName).orE‌​lse("empty-name");. by Jacob van Lingen, 15.04.2021 06:09
Show remaining 2 comments
3
129

Depending on what kind of objects you are checking you may be able to use some of the classes in the apache commons such as: apache commons lang and apache commons collections

Example:

String foo;
...
if( StringUtils.isBlank( foo ) ) {
   ///do something
}

or (depending on what you need to check):

String foo;
...
if( StringUtils.isEmpty( foo ) ) {
   ///do something
}

The StringUtils class is only one of many; there are quite a few good classes in the commons that do null safe manipulation.

Here follows an example of how you can use null vallidation in JAVA when you include apache library(commons-lang-2.4.jar)

public DOCUMENT read(String xml, ValidationEventHandler validationEventHandler) {
    Validate.notNull(validationEventHandler,"ValidationHandler not Injected");
    return read(new StringReader(xml), true, validationEventHandler);
}

And if you are using Spring, Spring also has the same functionality in its package, see library(spring-2.4.6.jar)

Example on how to use this static classf from spring(org.springframework.util.Assert)

Assert.notNull(validationEventHandler,"ValidationHandler not Injected");
07.11.2008 09:10
Comments
Also you can use the more generic version from Apache Commons, quite useful at the start of methods to check params I find. Validate.notNull( object, "object must not be null"); commons.apache.org/lang/apidocs/org/apache/commons/lang/… by monojohnny, 14.01.2010 13:57
@monojohnny does Validate use Assert statements into?. i ask that because Assert may be activate / deactivate on JVM and it's suggest do not use in production. by Kurapika, 09.12.2017 16:03
Don't think so - I believe it just throws a RuntimeException if validation fails by monojohnny, 06.01.2018 14:45
1
101
  • If you consider an object should not be null (or it is a bug) use an assert.
  • If your method doesn't accept null params say it in the javadoc and use an assert.

You have to check for object != null only if you want to handle the case where the object may be null...

There is a proposal to add new annotations in Java7 to help with null / notnull params: http://tech.puredanger.com/java7/#jsr308

07.11.2008 08:55
Comments
No, do not use assertions in production code. by phil294, 26.02.2017 00:54
1
93

I'm a fan of "fail fast" code. Ask yourself - are you doing something useful in the case where the parameter is null? If you don't have a clear answer for what your code should do in that case... I.e. it should never be null in the first place, then ignore it and allow a NullPointerException to be thrown. The calling code will make just as much sense of an NPE as it would an IllegalArgumentException, but it'll be easier for the developer to debug and understand what went wrong if an NPE is thrown rather than your code attempting to execute some other unexpected contingency logic - which ultimately results in the application failing anyway.

23.05.2011 18:18
Comments
better to use assertions, i.e Contract.notNull(abc, "abc must be non-null, did it fail to load during xyz?"); - this is a more compact way than doing an if (abc!=null) { throw new RuntimeException...} by ianpojman, 18.10.2012 03:35
8
79

The Google collections framework offers a good and elegant way to achieve the null check.

There is a method in a library class like this:

static <T> T checkNotNull(T e) {
   if (e == null) {
      throw new NullPointerException();
   }
   return e;
}

And the usage is (with import static):

...
void foo(int a, Person p) {
   if (checkNotNull(p).getAge() > a) {
      ...
   }
   else {
      ...
   }
}
...

Or in your example:

checkNotNull(someobject).doCalc();
29.12.2008 13:50
Comments
mmm, what is the difference? p.getAge() would throw the same NPE with less overhead and a clearer stack trace. What am I missing? by mysomic, 18.05.2009 23:26
It is better to throw an IllegalArgumentException("e == null") in your example as it clearly indicates that it is a programmer-intended exception (along with enough information to actually allow the maintainer to identify the problem). NullPointerExceptions should be reserved for the JVM, as it then clearly indicates that this was unintentional (and usually happens somewhere hard to identify) by Thorbjørn Ravn Andersen, 26.05.2009 11:56
This is now part of Google Guava. by Steven Benitez, 13.02.2011 20:55
Smells like over-engineering to me. Just let the JVM throw an NPE and don't clutter your code with this junk. by Alex Worden, 23.04.2012 19:11
I like it and open most methods and constructors with explicit checks on the arguments; if there is an error, methods always fail on the first few lines and I know the offending reference without finding something like getThing().getItsThing().getOtherThing().wowEncapsulationIsB‌​roken().setLol("hi")‌​; by Cory Kendall, 22.11.2012 06:26
Java 1.7 added the java.util.Objects.requireNonNull method (amongst others) that does exactly this. It's such a common idiom that I'm amazed it took this long! by Matt, 13.08.2014 04:09
just for interest... what is the difference between checkNotNull(bla).foo() and bla.foo() if both may throw a NPE in case of null? zero benefits, right? by gorefest, 29.10.2018 19:01
@gorefest checkNotNull returns the value, so you can assign your fields in constructor with it. E.g. this.foo = checkNotNull(foo), also more readable (it shows you want to enforce non nulls, not some random method call), also what if the param has no methods to call, or methods require many arguments. Lastly checkNotNull supports custom error message. by wilmol, 22.07.2019 02:15
Show remaining 3 comments
18
75

Null is not a 'problem'. It is an integral part of a complete modeling tool set. Software aims to model the complexity of the world and null bears its burden. Null indicates 'No data' or 'Unknown' in Java and the like. So it is appropriate to use nulls for these purposes. I don't prefer the 'Null object' pattern; I think it rise the 'who will guard the guardians' problem.
If you ask me what is the name of my girlfriend I'll tell you that I have no girlfriend. In the Java language I'll return null. An alternative would be to throw meaningful exception to indicate some problem that can't be (or don't want to be) solved right there and delegate it somewhere higher in the stack to retry or report data access error to the user.

  1. For an 'unknown question' give 'unknown answer'. (Be null-safe where this is correct from business point of view) Checking arguments for null once inside a method before usage relieves multiple callers from checking them before a call.

    public Photo getPhotoOfThePerson(Person person) {
        if (person == null)
            return null;
        // Grabbing some resources or intensive calculation
        // using person object anyhow.
    }
    

    Previous leads to normal logic flow to get no photo of a non-existent girlfriend from my photo library.

    getPhotoOfThePerson(me.getGirlfriend())
    

    And it fits with new coming Java API (looking forward)

    getPhotoByName(me.getGirlfriend()?.getName())
    

    While it is rather 'normal business flow' not to find photo stored into the DB for some person, I used to use pairs like below for some other cases

    public static MyEnum parseMyEnum(String value); // throws IllegalArgumentException
    public static MyEnum parseMyEnumOrNull(String value);
    

    And don't loathe to type <alt> + <shift> + <j> (generate javadoc in Eclipse) and write three additional words for you public API. This will be more than enough for all but those who don't read documentation.

    /**
     * @return photo or null
     */
    

    or

    /**
     * @return photo, never null
     */
    
  2. This is rather theoretical case and in most cases you should prefer java null safe API (in case it will be released in another 10 years), but NullPointerException is subclass of an Exception. Thus it is a form of Throwable that indicates conditions that a reasonable application might want to catch (javadoc)! To use the first most advantage of exceptions and separate error-handling code from 'regular' code (according to creators of Java) it is appropriate, as for me, to catch NullPointerException.

    public Photo getGirlfriendPhoto() {
        try {
            return appContext.getPhotoDataSource().getPhotoByName(me.getGirlfriend().getName());
        } catch (NullPointerException e) {
            return null;
        }
    }
    

    Questions could arise:

    Q. What if getPhotoDataSource() returns null?
    A. It is up to business logic. If I fail to find a photo album I'll show you no photos. What if appContext is not initialized? This method's business logic puts up with this. If the same logic should be more strict then throwing an exception it is part of the business logic and explicit check for null should be used (case 3). The new Java Null-safe API fits better here to specify selectively what implies and what does not imply to be initialized to be fail-fast in case of programmer errors.

    Q. Redundant code could be executed and unnecessary resources could be grabbed.
    A. It could take place if getPhotoByName() would try to open a database connection, create PreparedStatement and use the person name as an SQL parameter at last. The approach for an unknown question gives an unknown answer (case 1) works here. Before grabbing resources the method should check parameters and return 'unknown' result if needed.

    Q. This approach has a performance penalty due to the try closure opening.
    A. Software should be easy to understand and modify firstly. Only after this, one could think about performance, and only if needed! and where needed! (source), and many others).

    PS. This approach will be as reasonable to use as the separate error-handling code from "regular" code principle is reasonable to use in some place. Consider the next example:

    public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
        try {
            Result1 result1 = performSomeCalculation(predicate);
            Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
            Result3 result3 = performThirdCalculation(result2.getSomeProperty());
            Result4 result4 = performLastCalculation(result3.getSomeProperty());
            return result4.getSomeProperty();
        } catch (NullPointerException e) {
            return null;
        }
    }
    
    public SomeValue calculateSomeValueUsingSophisticatedLogic(Predicate predicate) {
        SomeValue result = null;
        if (predicate != null) {
            Result1 result1 = performSomeCalculation(predicate);
            if (result1 != null && result1.getSomeProperty() != null) {
                Result2 result2 = performSomeOtherCalculation(result1.getSomeProperty());
                if (result2 != null && result2.getSomeProperty() != null) {
                    Result3 result3 = performThirdCalculation(result2.getSomeProperty());
                    if (result3 != null && result3.getSomeProperty() != null) {
                        Result4 result4 = performLastCalculation(result3.getSomeProperty());
                        if (result4 != null) {
                            result = result4.getSomeProperty();
                        }
                    }
                }
            }
        }
        return result;
    }
    

    PPS. For those fast to downvote (and not so fast to read documentation) I would like to say that I've never caught a null-pointer exception (NPE) in my life. But this possibility was intentionally designed by the Java creators because NPE is a subclass of Exception. We have a precedent in Java history when ThreadDeath is an Error not because it is actually an application error, but solely because it was not intended to be caught! How much NPE fits to be an Error than ThreadDeath! But it is not.

  3. Check for 'No data' only if business logic implies it.

    public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
        if (personId == null)
            return;
        DataSource dataSource = appContext.getStuffDataSource();
        Person person = dataSource.getPersonById(personId);
        if (person != null) {
            person.setPhoneNumber(phoneNumber);
            dataSource.updatePerson(person);
        } else {
            Person = new Person(personId);
            person.setPhoneNumber(phoneNumber);
            dataSource.insertPerson(person);
        }
    }
    

    and

    public void updatePersonPhoneNumber(Long personId, String phoneNumber) {
        if (personId == null)
            return;
        DataSource dataSource = appContext.getStuffDataSource();
        Person person = dataSource.getPersonById(personId);
        if (person == null)
            throw new SomeReasonableUserException("What are you thinking about ???");
        person.setPhoneNumber(phoneNumber);
        dataSource.updatePerson(person);
    }
    

    If appContext or dataSource is not initialized unhandled runtime NullPointerException will kill current thread and will be processed by Thread.defaultUncaughtExceptionHandler (for you to define and use your favorite logger or other notification mechanizm). If not set, ThreadGroup#uncaughtException will print stacktrace to system err. One should monitor application error log and open Jira issue for each unhandled exception which in fact is application error. Programmer should fix bug somewhere in initialization stuff.

21.11.2011 12:58
Comments
Just because it was intended to mean "no data" doesn't mean it should be used. The language implementation of null sucks. by Mechanical snail, 17.08.2012 07:00
Catching NullPointerException and returning null is horrible to debug. You end up with NPE later on anyway, and it's really hard to figure out what was originally null. by artbristol, 14.09.2013 08:44
The problem with your example is that getPhotoOfThePerson really has no business deciding whether or not to return a photo or how to deal with a null person -- a straightforward reading of the method name indicates that it returns a photo of a person. It shouldn't return null because it doesn't (and shouldn't) know how the caller will handle a null photo. The caller on the other hand should know what to do when the person is null. Java doesn't have null propogation, which would eliminate the problem, as then it would know enough about how nulls are handled to go ahead and use it. by jmoreno, 18.11.2013 06:18
I'd downvote if I had the reputation. Not only is null not necessary, it's a hole in the type system. Assigning a Tree to a List is a type error because trees are not values of type List; by that same logic, assigning null should be a type error because null is not a value of type Object, or any useful type for that matter. Even the man that invented null considers it his "billion-dollar mistake". The notion of "a value that might be a value of type T OR nothing" is its own type, and should be represented as such (e.g. Maybe<T> or Optional<T>). by Doval, 20.11.2013 15:57
As of "Assigning a Tree to a List" you were not talking about Java, did you? Because Java is 'compile time strict type' language (it's memory model differ from C++, C# though). Java compiler will not give you an opportunity to assign Tree to a List. by Mike, 01.04.2014 09:56
As of "Maybe<T> or Optional<T>" you still need to write code like if (maybeNull.hasValue()) {...} so what is the difference with if (maybeNull != null)) {...}? by Mike, 01.04.2014 11:06
As of "Java doesn't have null propagation, which would eliminate the problem", usually propagation is about 'exceptional cases'. But data availability or non-availability is a common business flow in most cases. If it is something exceptional in data non-availability (which is dictated by business) you should explicitly throw reasonable exception with a reasonable message. Null propagation (with line number inside?..) would be really horrible as for me. by Mike, 01.04.2014 11:17
As of "catching NullPointerException and returning null is horrible to debug. You end up with NPE later on anyway, and it's really hard to figure out what was originally null". I'm totally agree! In those cases you should write a dozen of 'if' statements or throw NPE if business logic imply data in-place, or use null-safe operator from new Java. But there are cases when I don't care about what exact step give me null. For example calculating some values for the user just before showing on the screen when you do expect data could be missing. by Mike, 01.04.2014 11:32
@MykhayloAdamovych: The benefit of Maybe<T> or Optional<T> isn't in the case where your T might be null, but in the case where it should never be null. If you have a type that explicitly means "this value might be null -- use with caution", and you use and return such a type consistently, then whenever you see a plain old T in your code, you can assume it is never null. (Course, this would be a lot more useful if enforceable by the compiler.) by cHao, 07.11.2014 19:55
Agree. But you'll not reduce 'checks for emptiness' in your code (the topic we are discussing), you'll be more safe though but it comes at a price. by Mike, 23.12.2014 17:50
"Even the man that invented null considers it his "billion-dollar mistake" - null was there before anything was invented. One can invent set of rules to deal with it in specific way but this will be 'just another functionally complete system'. I would like to know how much would it cost to deal with subtle bugs in such non fail fast system. May be we are close to compare such systems because of new trends. by Mike, 05.02.2015 11:32
"The notion of "a value that might be a value of type T OR nothing" is its own type, and should be represented as such (e.g. Maybe<T> or Optional<T>)" - you may think that all references in Java are Optional<T> and you may switch to DefinetlyInitialized<T> by for using underused final keyword or introduce Mandatory<T>. So what's the difference?.. Anyway I like current Java defaults more because things around us are rather optional. It is optional for 'the kettle to be filled with water before cooking', and that 'there is some fuel in the car before you leave' etc. by Mike, 06.02.2015 17:03
Currently reading some Oracle Database Reference about 'Null Values in Arithmetic Expressions'. It states: 'If any column value in an arithmetic expression is null, the result is null. For example, if you attempt to perform division by zero, you get an error. However, if you divide a number by null, the result is a null or unknown.' But don't mind, this is totally not logical, there should be some silly guy somewhere at Oracle and he must be fired till these days... by Mike, 19.07.2016 10:52
@MykhayloAdamovych: If meaningful values for array items will become known in arbitrary sequence, and it will be necessary to read some array items before meaningful values have been assigned to all of them, it will generally not be possible to statically rule out the possibility that items will be read before a meaningful value has been determined. If Hoare doesn't like nulls, I'm curious what kind of default value or behavior he'd prefer? Trapping when a null is read from the array might sometimes be better than waiting until it is dereferenced, but would make it impossible to copy... by supercat, 11.08.2016 22:41
...a partially-populated array by iteratively copying the items therein. The only other choices I can see is to say that attempting to dereference a pointer read from an array slot that hasn't yet been written will access some default object (which would for most purposes seem rather silly) or will have C-style "Undefined Behavior". I'd say trapping null pointers are better than any alternative I can see. by supercat, 11.08.2016 22:45
@MykhayloAdamovych see how Swift does it, which is how many others did before. If Java simply didn't have null, you'd have no way to store a null into a field/variable; to handle the case where it's optional, you'd have to have an Optional<T>. And you ask - what would that gain? Wouldn't you need as many checks? No, you wouldn't, because the compiler would ensure that every non-Optional was never null, and more than half our checks are with objects that never should be null and never are, or if they are then that's a bug that would either be caught by the compiler or exposed by the interface. by entonio, 31.07.2017 19:39
@entonio i don't follow, After the compiler ensures that the Optional (or what ever) is not null then what? Are you saying that the Person application is designed to never encounter a situation where someone does not have a girlfriend? How does the application handle those scenarios, are there multiple types of Person, maybe we create 2 types of Person, LonelyPerson and ShackledPerson? by Boo, 17.08.2017 23:54
@entonio, Java has Optional<T>, that is non-final reference. And Java's compiler ensures that every final is initialized. And you would have the same amount of checks if you are senior enough not to write boilerplate code because 'emptiness' is a business notion. And Java's Optional<T> is free from get() and put() boilerplate. by Mike, 20.08.2017 20:18
Show remaining 13 comments
3
79

Rather than Null Object Pattern -- which has its uses -- you might consider situations where the null object is a bug.

When the exception is thrown, examine the stack trace and work through the bug.

07.11.2008 08:50
Comments
Problem is that usually you loose context as the NullPointerException does not indicate WHICH variable was null, and you may have several "."-operations on the line. Using "if (foo == null) throw new RuntimeException("foo == null")" allows you to state explicitly WHAT was wrong, giving your stack trace much more value to those who have to fix it. by Thorbjørn Ravn Andersen, 31.10.2009 09:02
With Andersen - I would love Java's exception system to be able to include the name of a variable that's being worked upon, so that NullPointerExceptions would not only indicate the line the exception occurred on, but also the variable name. This should work just fine in unobfuscated software. by cthulhu, 18.01.2011 12:53
I had a professor that preached against method call chaining. His theory was that you should be wary of call chains that were longer than 2 methods. I don't know if that's a hard rule, but it definitely removes most of the problems with NPE stack traces. by RustyTheBoyRobot, 16.04.2013 17:12
2
78

Sometimes, you have methods that operate on its parameters that define a symmetric operation:

a.f(b); <-> b.f(a);

If you know b can never be null, you can just swap it. It is most useful for equals: Instead of foo.equals("bar"); better do "bar".equals(foo);.

07.11.2008 09:04
Comments
But then you have to assume equals (could be any method) will handle null correctly. Really all this is doing is passing the responsibility to someone else (or another method). by Supericy, 13.06.2013 20:01
@Supericy Basically yes, but equals (or whatever method) has to check for null anyway. Or state explicitly that it does not. by Angelo Fuchs, 30.07.2013 07:26
7
71

Java 7 has a new java.util.Objects utility class on which there is a requireNonNull() method. All this does is throw a NullPointerException if its argument is null, but it cleans up the code a bit. Example:

Objects.requireNonNull(someObject);
someObject.doCalc();

The method is most useful for checking just before an assignment in a constructor, where each use of it can save three lines of code:

Parent(Child child) {
   if (child == null) {
      throw new NullPointerException("child");
   }
   this.child = child;
}

becomes

Parent(Child child) {
   this.child = Objects.requireNonNull(child, "child");
}
10.08.2012 07:08
Comments
Actually, your example constitutes code bloat: the first line is superfluous because the NPE would be thrown in the second line. ;-) by user1050755, 07.03.2013 01:21
True. A better example would be if the second line were doCalc(someObject). by Stuart Marks, 07.03.2013 05:23
Depends. If you are the author of doCalc(), I'd suggest putting the check into that method's body (if possible). And then you most likely will call someObject.someMethod() where again there is no need to check for null. :-) by user1050755, 07.03.2013 07:07
Well, if you are not the author of doCalc(), and it doesn't immediately throw NPE when given null, you'd need to check for null and throw NPE yourself. That's what Objects.requireNonNull() is for. by Stuart Marks, 09.03.2013 06:43
It's not just code bloat. Better to check up front than halfway through a method that causes side effects or uses time/space. by Rob Grant, 26.09.2013 11:33
I probably wouldn't have thrown an NPE, when I'm argument checking for nulls I usually throw an IllegalArgumentException, and it's not a bad thing to do at the very top, if you assume this.child = child will "catch" it, you aren't being explicit in your code, a refactor could make it really tough to catch where the null originated. Code bloat is much better than magic, any day. by Bill K, 23.07.2014 17:55
The Objects.requireNonNull(object, string) version (where you can pass an error message as 2nd argument) is more useful than the single-arg version (the latter probably just added for the sake of completeness), especially when you're using it to check multiple argument values. Say you had to check 3 arguments for null, this would reduce your code from 3 if/then-throw blocks (separated by empty lines), to 3 single lines not needing empty lines. by Cornel Masson, 09.10.2014 15:05
Show remaining 2 comments
1
52

Ultimately, the only way to completely solve this problem is by using a different programming language:

  • In Objective-C, you can do the equivalent of invoking a method on nil, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.
  • In Nice, a Java-derived language, there are two versions of all types: a potentially-null version and a not-null version. You can only invoke methods on not-null types. Potentially-null types can be converted to not-null types through explicit checking for null. This makes it much easier to know where null checks are necessary and where they aren't.
29.07.2009 20:52
Comments
I am not familiar with Nice, but Kotlin implements the same idea, have nullable and not-null types build into the language's type system. A lot more concise than Optionals or null Object pattern. by mtsahakis, 17.09.2018 19:29
4
37

In addition to using assert you can use the following:

if (someobject == null) {
    // Handle null here then move on.
}

This is slightly better than:

if (someobject != null) {
    .....
    .....



    .....
}
17.08.2010 03:59
Comments
Mh, why that? Please don't feel any defensive, I'd just like to learn more about Java :) by Matthias Meid, 17.08.2010 05:54
@Mudu As a general rule, I prefer the expression in an if statement to be a more "positive" statement, rather than a "negative" one. So if I saw if (!something) { x(); } else { y(); } I would be inclined to refactor it as if (something) { y(); } else { x(); } (though one could argue that != null is the more positive option...). But more importantly, the important part of the code is not wrapped inside {}s and you have one level less of indentation for most of the method. I don't know if that was fastcodejava's reasoning but that would be mine. by MatrixFrog, 22.06.2011 00:05
This is what I tend to do as well.. Keeps the code clean in my opinon. by Koray Tugay, 15.12.2015 21:44
@MatrixFrog Yeah that makes the code cleaner and easily readable, as you see the important code (when everything function without errors) first. by Skaldebane, 22.06.2020 22:41
1
38

Common "problem" in Java indeed.

First, my thoughts on this:

I consider that it is bad to "eat" something when NULL was passed where NULL isn't a valid value. If you're not exiting the method with some sort of error then it means nothing went wrong in your method which is not true. Then you probably return null in this case, and in the receiving method you again check for null, and it never ends, and you end up with "if != null", etc..

So, IMHO, null must be a critical error which prevents further execution (that is, where null is not a valid value).

The way I solve this problem is this:

First, I follow this convention:

  1. All public methods / API always check its arguments for null
  2. All private methods do not check for null since they are controlled methods (just let die with nullpointer exception in case it wasn't handled above)
  3. The only other methods which do not check for null are utility methods. They are public, but if you call them for some reason, you know what parameters you pass. This is like trying to boil water in the kettle without providing water...

And finally, in the code, the first line of the public method goes like this:

ValidationUtils.getNullValidator().addParam(plans, "plans").addParam(persons, "persons").validate();

Note that addParam() returns self, so that you can add more parameters to check.

Method validate() will throw checked ValidationException if any of the parameters is null (checked or unchecked is more a design/taste issue, but my ValidationException is checked).

void validate() throws ValidationException;

The message will contain the following text if, for example, "plans" is null:

"Illegal argument value null is encountered for parameter [plans]"

As you can see, the second value in the addParam() method (string) is needed for the user message, because you cannot easily detect passed-in variable name, even with reflection (not subject of this post anyway...).

And yes, we know that beyond this line we will no longer encounter a null value so we just safely invoke methods on those objects.

This way, the code is clean, easy maintainable and readable.

15.03.2011 12:42
Comments
Absolutely. Applications that just throw the error and crash are of higher quality because there is no doubt when they are not working. Applications that swallow the errors at best degrade gracefully but usually don't work in ways that are difficult to notice and don't get fixed. And when the problem is noticed they are much harder to debug. by Paul Jackson, 14.11.2011 05:06
0
37

Asking that question points out that you may be interested in error handling strategies. How and where to handle errors is a pervasive architectural question. There are several ways to do this.

My favorite: allow the Exceptions to ripple through - catch them at the 'main loop' or in some other function with the appropriate responsibilities. Checking for error conditions and handling them appropriately can be seen as a specialized responsibility.

Sure do have a look at Aspect Oriented Programming, too - they have neat ways to insert if( o == null ) handleNull() into your bytecode.

07.11.2008 09:27
6
35

Just don't ever use null. Don't allow it.

In my classes, most fields and local variables have non-null default values, and I add contract statements (always-on asserts) everywhere in the code to make sure this is being enforced (since it's more succinct, and more expressive than letting it come up as an NPE and then having to resolve the line number, etc.).

Once I adopted this practice, I noticed that the problems seemed to fix themselves. You'd catch things much earlier in the development process just by accident and realize you had a weak spot.. and more importantly.. it helps encapsulate different modules' concerns, different modules can 'trust' each other, and no more littering the code with if = null else constructs!

This is defensive programming and results in much cleaner code in the long run. Always sanitize the data, e.g. here by enforcing rigid standards, and the problems go away.

class C {
    private final MyType mustBeSet;
    public C(MyType mything) {
       mustBeSet=Contract.notNull(mything);
    }
   private String name = "<unknown>";
   public void setName(String s) {
      name = Contract.notNull(s);
   }
}


class Contract {
    public static <T> T notNull(T t) { if (t == null) { throw new ContractException("argument must be non-null"); return t; }
}

The contracts are like mini-unit tests which are always running, even in production, and when things fail, you know why, rather than a random NPE you have to somehow figure out.

18.10.2012 03:42
Comments
why would this be downvoted? in my experience, this is far superior to the other approaches, would love to know why not by ianpojman, 31.10.2012 21:31
I agree, this approach prevents problems related to nulls, rather than fixing them by speckling code null checks everywhere. by ChrisBlom, 27.07.2013 10:48
The problem with this approach is that if name is never set, it has the value "<unknown>", which behaves like a set value. Now let's say I need to check if name was never set (unknown), I have to do a string comparison against the special value "<unknown>". by Steve Kuo, 17.12.2013 07:02
True good point Steve. What I often do is have that value as a constant, e.g. public static final String UNSET="__unset" ... private String field = UNSET ... then private boolean isSet() { return UNSET.equals(field); } by ianpojman, 26.01.2015 19:45
IMHO, This is a implementation of Null Object Pattern with a yourself implementation of Optional (Contract). How it behaves on persistence class class? I do not see applicable in that case. by Kurapika, 09.12.2017 19:56
@Kurapika - agree. I think "never use null" is not entirely practical in Java. But 99% of the time, it is, and is to be encouraged imo. I like what I see with languages like Kotlin that address this problem. by ianpojman, 12.12.2017 20:28
Show remaining 1 comments
1
31

Guava, a very useful core library by Google, has a nice and useful API to avoid nulls. I find UsingAndAvoidingNullExplained very helpful.

As explained in the wiki:

Optional<T> is a way of replacing a nullable T reference with a non-null value. An Optional may either contain a non-null T reference (in which case we say the reference is "present"), or it may contain nothing (in which case we say the reference is "absent"). It is never said to "contain null."

Usage:

Optional<Integer> possible = Optional.of(5);
possible.isPresent(); // returns true
possible.get(); // returns 5
23.03.2012 20:16
Comments
@CodyGuldner Right, Cody. I provided a relevant quote from the link to give more context. by Murat Derya Özen, 07.08.2014 21:05
1
26

This is a very common problem for every Java developer. So there is official support in Java 8 to address these issues without cluttered code.

Java 8 has introduced java.util.Optional<T>. It is a container that may or may not hold a non-null value. Java 8 has given a safer way to handle an object whose value may be null in some of the cases. It is inspired from the ideas of Haskell and Scala.

In a nutshell, the Optional class includes methods to explicitly deal with the cases where a value is present or absent. However, the advantage compared to null references is that the Optional<T> class forces you to think about the case when the value is not present. As a consequence, you can prevent unintended null pointer exceptions.

In above example we have a home service factory that returns a handle to multiple appliances available in the home. But these services may or may not be available/functional; it means it may result in a NullPointerException. Instead of adding a null if condition before using any service, let's wrap it in to Optional<Service>.

WRAPPING TO OPTION<T>

Let's consider a method to get a reference of a service from a factory. Instead of returning the service reference, wrap it with Optional. It lets the API user know that the returned service may or may not available/functional, use defensively

public Optional<Service> getRefrigertorControl() {
      Service s = new  RefrigeratorService();
       //...
      return Optional.ofNullable(s);
   }

As you see Optional.ofNullable() provides an easy way to get the reference wrapped. There are another ways to get the reference of Optional, either Optional.empty() & Optional.of(). One for returning an empty object instead of retuning null and the other to wrap a non-nullable object, respectively.

SO HOW EXACTLY IT HELPS TO AVOID A NULL CHECK?

Once you have wrapped a reference object, Optional provides many useful methods to invoke methods on a wrapped reference without NPE.

Optional ref = homeServices.getRefrigertorControl();
ref.ifPresent(HomeServices::switchItOn);

Optional.ifPresent invokes the given Consumer with a reference if it is a non-null value. Otherwise, it does nothing.

@FunctionalInterface
public interface Consumer<T>

Represents an operation that accepts a single input argument and returns no result. Unlike most other functional interfaces, Consumer is expected to operate via side-effects. It is so clean and easy to understand. In the above code example, HomeService.switchOn(Service) gets invoked if the Optional holding reference is non-null.

We use the ternary operator very often for checking null condition and return an alternative value or default value. Optional provides another way to handle the same condition without checking null. Optional.orElse(defaultObj) returns defaultObj if the Optional has a null value. Let's use this in our sample code:

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

Now HomeServices.get() does same thing, but in a better way. It checks whether the service is already initialized of not. If it is then return the same or create a new New service. Optional<T>.orElse(T) helps to return a default value.

Finally, here is our NPE as well as null check-free code:

import java.util.Optional;
public class HomeServices {
    private static final int NOW = 0;
    private static Optional<HomeServices> service;

public static Optional<HomeServices> get() {
    service = Optional.of(service.orElse(new HomeServices()));
    return service;
}

public Optional<Service> getRefrigertorControl() {
    Service s = new  RefrigeratorService();
    //...
    return Optional.ofNullable(s);
}

public static void main(String[] args) {
    /* Get Home Services handle */
    Optional<HomeServices> homeServices = HomeServices.get();
    if(homeServices != null) {
        Optional<Service> refrigertorControl = homeServices.get().getRefrigertorControl();
        refrigertorControl.ifPresent(HomeServices::switchItOn);
    }
}

public static void switchItOn(Service s){
         //...
    }
}

The complete post is NPE as well as Null check-free code … Really?.

27.04.2015 04:16
Comments
There's a null check in above code - if(homeServices != null) { which can be changed to homeServices.ifPresent(h -> //action); by KrishPrabakar, 02.01.2020 12:36
2
23

I like articles from Nat Pryce. Here are the links:

In the articles there is also a link to a Git repository for a Java Maybe Type which I find interesting, but I don't think it alone could decrease the checking code bloat. After doing some research on the Internet, I think != null code bloat could be decreased mainly by careful design.

21.08.2011 18:33
Comments
Michael Feathers has written an short and interesthing text about approaches like the one you mentioned: manuelp.newsblur.com/site/424 by ivan.aguirre, 12.07.2013 20:59
If there's anything I appreciated most about this answer, it's the "careful design" tip. Whether it boils down to writing code, fixing bugs or checking for nullity, it's DAMN CRUCIAL to make an overall good design and organisation in code, to avoid many redundancies that we still have to deal with today because of bad design choices made a long time ago... by Skaldebane, 24.06.2020 21:49
0
22

I've tried the NullObjectPattern but for me is not always the best way to go. There are sometimes when a "no action" is not appropiate.

NullPointerException is a Runtime exception that means it's developers fault and with enough experience it tells you exactly where is the error.

Now to the answer:

Try to make all your attributes and its accessors as private as possible or avoid to expose them to the clients at all. You can have the argument values in the constructor of course, but by reducing the scope you don't let the client class pass an invalid value. If you need to modify the values, you can always create a new object. You check the values in the constructor only once and in the rest of the methods you can be almost sure that the values are not null.

Of course, experience is the better way to understand and apply this suggestion.

Byte!

13.11.2008 22:08
0
20

Probably the best alternative for Java 8 or newer is to use the Optional class.

Optional stringToUse = Optional.of("optional is there");
stringToUse.ifPresent(System.out::println);

This is especially handy for long chains of possible null values. Example:

Optional<Integer> i = Optional.ofNullable(wsObject.getFoo())
    .map(f -> f.getBar())
    .map(b -> b.getBaz())
    .map(b -> b.getInt());

Example on how to throw exception on null:

Optional optionalCarNull = Optional.ofNullable(someNull);
optionalCarNull.orElseThrow(IllegalStateException::new);

Java 7 introduced the Objects.requireNonNull method which can be handy when something should be checked for non-nullness. Example:

String lowerVal = Objects.requireNonNull(someVar, "input cannot be null or empty").toLowerCase();
23.03.2016 00:03
1
17

May I answer it more generally!

We usually face this issue when the methods get the parameters in the way we not expected (bad method call is programmer's fault). For example: you expect to get an object, instead you get a null. You expect to get an String with at least one character, instead you get an empty String ...

So there is no difference between:

if(object == null){
   //you called my method badly!

}

or

if(str.length() == 0){
   //you called my method badly again!
}

They both want to make sure that we received valid parameters, before we do any other functions.

As mentioned in some other answers, to avoid above problems you can follow the Design by contract pattern. Please see http://en.wikipedia.org/wiki/Design_by_contract.

To implement this pattern in java, you can use core java annotations like javax.annotation.NotNull or use more sophisticated libraries like Hibernate Validator.

Just a sample:

getCustomerAccounts(@NotEmpty String customerId,@Size(min = 1) String accountType)

Now you can safely develop the core function of your method without needing to check input parameters, they guard your methods from unexpected parameters.

You can go a step further and make sure that only valid pojos could be created in your application. (sample from hibernate validator site)

public class Car {

   @NotNull
   private String manufacturer;

   @NotNull
   @Size(min = 2, max = 14)
   private String licensePlate;

   @Min(2)
   private int seatCount;

   // ...
}
12.02.2014 11:41
Comments
javax is, by definition, not "core Java". by Tomas, 30.10.2015 04:02
4
17

I highly disregard answers that suggest using the null objects in every situation. This pattern may break the contract and bury problems deeper and deeper instead of solving them, not mentioning that used inappropriately will create another pile of boilerplate code that will require future maintenance.

In reality if something returned from a method can be null and the calling code has to make decision upon that, there should an earlier call that ensures the state.

Also keep in mind, that null object pattern will be memory hungry if used without care. For this - the instance of a NullObject should be shared between owners, and not be an unigue instance for each of these.

Also I would not recommend using this pattern where the type is meant to be a primitive type representation - like mathematical entities, that are not scalars: vectors, matrices, complex numbers and POD(Plain Old Data) objects, which are meant to hold state in form of Java built-in types. In the latter case you would end up calling getter methods with arbitrary results. For example what should a NullPerson.getName() method return?

It's worth considering such cases in order to avoid absurd results.

12.04.2014 13:27
Comments
The solution with "hasBackground()" has one drawback - it's not thread-safe. If you need to call two methods instead of one, you need to synchronize the whole sequence in multi-threaded environment. by pkalinow, 03.02.2016 12:26
@pkalinow You made a contrived example only to point out that this solution has a drawback. If code is not meant to run in multithreaded application then there is no drawback. I could put at you probably 90% of your code that is not thread safe. We're not speaking here about this aspect of code, we're speaking about design pattern. And multithreading is a topic on its own. by luke1985, 03.02.2016 15:29
Of course in a single-thread application it's not a problem. I've given that comment because sometimes it is a problem. by pkalinow, 04.02.2016 10:34
@pkalinow If you study this topic closer you will find out that Null Object design pattern won't fix the multithreading problems. So it's irrelevant. And to be honest, I've found places where this pattern would fit in nicely, so my original answer is a bit wrong, actually. by luke1985, 04.02.2016 10:57
2
16
  1. Never initialise variables to null.
  2. If (1) is not possible, initialise all collections and arrays to empty collections/arrays.

Doing this in your own code and you can avoid != null checks.

Most of the time null checks seem to guard loops over collections or arrays, so just initialise them empty, you won't need any null checks.

// Bad
ArrayList<String> lemmings;
String[] names;

void checkLemmings() {
    if (lemmings != null) for(lemming: lemmings) {
        // do something
    }
}



// Good
ArrayList<String> lemmings = new ArrayList<String>();
String[] names = {};

void checkLemmings() {
    for(lemming: lemmings) {
        // do something
    }
}

There is a tiny overhead in this, but it's worth it for cleaner code and less NullPointerExceptions.

14.06.2013 13:05
Comments
stackoverflow.com/questions/1386275/… by Terence, 01.07.2013 07:45
+1 This I agree with. You should never return half initialized objects. Jaxb related code and bean code is notiroius for this. It is bad practice. All collections should be initialized, and all objects should exist with (ideally) no null references. Consider a object that has a collection in it. Checking that the object is not null, that the collection is not null and that the collection does not contain null objects is unreasonable and foolish. by ggb667, 23.09.2013 14:52
2
11
public static <T> T ifNull(T toCheck, T ifNull) {
    if (toCheck == null) {
           return ifNull;
    }
    return toCheck;
}
13.10.2010 15:14
Comments
What's wrong with this method, I think @tltester just want to give a default value if the it's null, which make sense. by Sawyer, 17.08.2011 05:42
There is such a method in Apache commons-lang: ObjectUtils.defaultIfNull(). There is one more general: ObjectUtils.firstNonNull(), which can be used to implement a degrading strategy: firstNonNull(bestChoice, secondBest, thirdBest, fallBack); by ivant, 16.04.2015 08:04
1
15

This is the most common error occurred for most of the developers.

We have number of ways to handle this.

Approach 1:

org.apache.commons.lang.Validate //using apache framework

notNull(Object object, String message)

Approach 2:

if(someObject!=null){ // simply checking against null
}

Approach 3:

@isNull @Nullable  // using annotation based validation

Approach 4:

// by writing static method and calling it across whereever we needed to check the validation

static <T> T isNull(someObject e){  
   if(e == null){
      throw new NullPointerException();
   }
   return e;
}
11.04.2014 20:14
Comments
Ad. 4. It is not very useful - when you check if a pointer is null, you probably want to call a method on it. Calling a method on null gives you the same behavior - NullPointerException. by pkalinow, 03.02.2016 12:18
1
11

All in all to avoid statement

if (object != null) {
    ....
}
  1. since java 7 you can use Objects methods:

    Objects.isNull(object)

    Objects.nonNull(object)

    Objects.requireNonNull(object)

    Objects.equals(object1, object2)

  2. since java 8 you can use Optional class (when to use)

object.ifPresent(obj -> ...); java 8

object.ifPresentOrElse(obj -> ..., () -> ...); java 9

  1. rely on method contract (JSR 305) and use Find Bugs. Mark your code with annotations @javax.annotation.Nullable and @javax.annotation.Nonnnul. Also Preconditions are available.

    Preconditions.checkNotNull(object);

  2. In special cases (for example for Strings and Collections) you can use apache-commons (or Google guava) utility methods:

public static boolean isEmpty(CharSequence cs) //apache CollectionUtils

public static boolean isEmpty(Collection coll) //apache StringUtils

public static boolean isEmpty(Map map) //apache MapUtils

public static boolean isNullOrEmpty(@Nullable String string) //Guava Strings

  1. When you need to assign default value when null use apache commons lang

public static Object defaultIfNull(Object object, Object defaultValue)

14.11.2017 11:57
Comments
explain very well by Brijesh Mavani, 17.01.2018 16:56
0
10

Java 8 has introduced a new class Optional in java.util package.

Advantages of Java 8 Optional:

1.) Null checks are not required.
2.) No more NullPointerException at run-time.
3.) We can develop clean and neat APIs.

Optional - A container object which may or may not contain a non-null value. If a value is present, isPresent() will return true and get() will return the value.

For more details find here oracle docs :- https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html

09.10.2017 10:35
0
8

You can use FindBugs. They also have an Eclipse plugin) that helps you find duplicate null checks (among other things), but keep in mind that sometimes you should opt for defensive programming. There is also Contracts for Java which may be helpful.

10.03.2011 22:00
4
6

One more alternative:

The following simple function helps to hide the null-check (I don't know why, but I haven't found it as part of the same common library):

public static <T> boolean isNull(T argument) {
    return (argument == null);
}

You could now write

if (!isNull(someobject)) {
    someobject.doCalc();
}

which is IMO a better way of expressing != null.

21.10.2011 09:02
Comments
If you're constantly going to negate the return value, wouldn't it be better to simply write a function isNotNull? Doesn't that more clearly indicate your intent? by TMN, 22.11.2011 20:07
@TMN: your are right, ideally I'd like to have both a isNull and isNotNull method. by jeha, 22.11.2011 20:14
I fail to see how this is more concise than "someobject != null". by user1050755, 07.03.2013 01:27
Compile-time and run-time dev tools like findbugs will have a harder time identifying duplicate null checks. Also, you better hope Java inlines that isNull function, by IceArdor, 12.05.2017 08:28
0
8

I follow below guidelines to avoid null checks.

  1. Avoid lazy initialization of member variables as much as possible. Initialize the variables in declaration itself. This will handle NullPointerExceptions.

  2. Decide on mutability of member variables early in the cycle. Use language constructs like final keyword effectively.

  3. If you know that augments for method won't be changed, declare them as final.

  4. Limit the mutation of data as much as possible. Some variables can be created in a constructor and can never be changed. Remove public setter methods unless they are really required.

    E.g. Assume that one class in your application (A.java) is maintaining a collection like HashMap. Don't provide public getter method in A.java and allow B.java to directly add an element in Map. Instead provide an API in A.java, which adds an element into collection.

    // Avoid
    a.getMap().put(key,value)
    
    //recommended
    
    public void addElement(Object key, Object value){
           // Have null checks for both key and value here : single place
           map.put(key,value);
    }
    
  5. And finally, use try{} catch{} finally{} blocks at right places effectively.

25.01.2016 15:42
0
6

Wherever you pass an array or a Vector, initialise these to empty ones, instead of null. - This way you can avoid lots of checking for null and all is good :)

public class NonNullThing {

   Vector vectorField = new Vector();

   int[] arrayField = new int[0];

   public NonNullThing() {

      // etc

   }

}
07.11.2008 10:43
3
7

If you are using java8 or later go for the isNull(yourObject) from java.util.Objects.

Example:-

String myObject = null;

Objects.isNull(myObject); //will return true

Usage: The below code returns a non null value (if the name is not null then that value will be returned else the default value will be returned).

final String name = "Jobin";
String nonNullValue = Optional.ofNullable(name).filter(Objects::nonNull).orElse("DefaultName");
04.07.2017 09:41
Comments
This is not much diferent from myObject == null and was introduced in Java8 for Predicates in the lambda feature. by PeterMmm, 07.07.2017 11:54
Objects.isNull() is available since Java8 (not Java7) by RealHowTo, 12.10.2018 14:04
@RealHowTo Thankd for pointing it out, I have updated the answer, Actually Objects is introduced in java7, isNull added to it later. by J J, 12.10.2018 22:43
0
7

Since Java 7 the class java.util.Objects exists.

But since Java 8, you can use Objects.isNull(var) and Objects.nonNull(var) methods of Objects class to do the null pointer check.

For example,

String var1 = null;
Date var2 = null;
Long var3 = null;

if(Objects.isNull(var1) && Objects.isNull(var2) && Objects.isNull(var3))
    System.out.println("All Null");
else if (Objects.nonNull(var1) && Objects.nonNull(var2) && Objects.nonNull(var3))
    System.out.println("All Not Null");
28.11.2016 09:29
0
6

I find Guava Preconditions to be very useful in this case. I don't like leaving nulls to null pointer exception since the only way to understand an NPE is by locating the line number. Line numbers in production version and development version can be different.

Using Guava Preconditions, I can check null parameters and define a meaningful exception message in one line.

For example,

Preconditions.checkNotNull(paramVal, "Method foo received null paramVal");
05.03.2014 22:44
3
6

You can avoid most a lot to avoid NullPointerException by just following most of the others answers to the Question, I just want to add few more ways which have been introduced in Java 9 to handle this scenario gracefully and also showcase a few of the older ones can also be used and thus reducing your efforts.

  1. public static boolean isNull(Object obj)

    Returns true if the provided reference is null otherwise returns false.

    Since Java 1.8

  2. public static boolean nonNull(Object obj)

    Returns true if the provided reference is non-null otherwise returns false.

    Since Java 1.8

  3. public static <T> T requireNonNullElse​(T obj, T defaultObj)

    Returns the first argument if it is non-null and otherwise returns the non-null second argument.

    Since Java 9

  4. public static <T> T requireNonNullElseGet​(T obj, Supplier<? extends T> supplier)

    Returns the first argument if it is non-null and otherwise returns the non-null value of supplier.get().

    Since Java 9

  5. public static <T> T requireNonNull​(T obj, Supplier<String> messageSupplier)

    Checks that the specified object reference is not null and throws a customized NullPointerException otherwise.

    Since Java 1.8

Further details about the above functions can be found here.

12.07.2018 17:35
Comments
you can see there are a lot of answers with many upvotes, what is special about your answer? by Ibo, 12.07.2018 18:00
I just wanted to add a few more functions made available with Java 9. by Mukesh A, 12.07.2018 18:04
then emphasize on it with a bold font at the beginning of your post by Ibo, 12.07.2018 18:31
0
6

Java 8 has introduced a new class Optional in java.util package. It is used to represent a value is present or absent. The main advantage of this new construct is that No more too many null checks and NullPointerException. It avoids any runtime NullPointerExceptions and supports us in developing clean and neat Java APIs or Applications. Like Collections and arrays, it is also a Container to hold at most one value.

Below are some useful link you can follow

https://www.mkyong.com/java8/java-8-optional-in-depth/

https://dzone.com/articles/java-8-optional-avoid-null-and

11.06.2019 12:39
9
2

OK, I now this has been technically answered a million times but I have to say this because this is an un-ending discussion with Java programmers.

Sorry but I disagree will almost all of above. The reason we have to be testing for null in Java is because must Java programmers don’t know how to handle memory.

I say this because I have a long experience programming in C++ and we don’t do this. In other words, you don’t need to. And note that, in Java, if you hit a dangling pointer you get a normal exception; in C++ this exception normally is not caught and terminates the program.

Don’t want to do this? Then follow some simple rules ala C/C++.

Don’t instantiate things so easily, think that every "new" can get you in lots of trouble and FOLLOW these simple rules.

A class shall access memory in only 3 ways ->

  1. It can "HAVE" class members, and they will follow these rules:

    1. ALL "HAS" members are created "new" in the constructor.
    2. You will close /de allocate in destructor or equivalent close() function in Java for that same class and in NO other.

This means that you need to have in mind (just like Java does) who is the owner or parent of each resource and respect that ownership. An object is only deleted by the class who created it. Also ->

  1. Some members will be "USED" but not own or "HAVE". This are "OWN" in another class and passed as arguments to the constructor. Since these are owned by another class, we will NEVER delete or close this, only the parent can.

  2. A method in a class can also instantiate local objects for internal use which will NEVER pass out side of the class, or they should have been normal "has" objects.

Finally for all this to work, you need to have a disciplined design with classes in hierarchy form and making no cycles.

Under this design, AND following the above rules, there is no way that a child class in a hierarchy design will ever access a pointer which was destroyed, because that means that a parent was destroyed before a child, which the hierarchical acyclic design will not allow it.

Finally, also remember when starting your system you should build from top to bottom of the hierarchy and destroy bottom to top. You will never have a null pointer anywhere, or someone is violating the rules.

13.07.2012 21:46
Comments
Agreed, albeit only conceptually. Yeah, one should HAVE A PLAN. But then you need programmers who CAN MAKE PLANS and have the ability to think logically and develop and maintain consistent patterns. And then there are employers whose main focus is money and wages ;-). And then start having a look at the JPA spec to get an impression of what constitutes a consistent pattern/plan and what it requires to develop and/or document it. by user1050755, 07.03.2013 01:19
This answer is relevant for C++ but not for a garbage collected language like Java. by artbristol, 14.09.2013 17:08
I respectfully disagree. Good memory handling in JAVA ( or almost any other language) will give you many benefits. From better stability as nullpointers reduced, better performance as lower memory footprint, to better design as relationships are better controlled. I will suggest that the sloppy memory management of many JAVA applications leds to frequent NPEs and memory leaks. by Alex Vaz, 24.09.2013 04:44
I most emphatically agree with what you wrote, and think it very unfortunate that Java makes no distinction between references that encapsulate ownership and those which do not. Those who would argue "that's what GC is for" miss a critical point: GC avoids the need for immutable objects to have owners, and it also eliminates the possibility of a dangling reference to a deleted object turning into a reference to some other arbitrary object (as can happen in C++). It's hard to write correct code, however, if more than one object encapsulates a mutable object's state as part of its own. by supercat, 04.11.2013 18:36
My preferred way of thinking of things is to say that references can encapsulate identity, mutable state, both, or neither. Additionally, references can encapsulate mutable state either because they identify an immutable object, or because the object they identify will never be exposed to anything that might mutate it. It's too bad Java has no concept of such distinctions, since things like equality checking and cloning could be handled 99% automatically if it did. by supercat, 04.11.2013 18:38
I believe what you suggest will only address a small subset of null pointer problems in Java, and will not solve the original problem described here. by Kemal Erdogan, 16.09.2014 14:51
It might be more relevant than you think. More info: ibm.com/developerworks/library/j-jtp06243 :) by Alex Vaz, 05.03.2015 22:45
"[.............]You will never have a null pointer anywhere, or someone is violating the rules." That one violating the rules is precisely the point of the question. Or you write 100% of your code without using a single library? by guido, 27.04.2015 17:00
Of course, you can not control other people's code. But the rules still apply, and are useful. Other wise, its like saying that, RUST ( cmr.github.io/blog/2013/08/13/rust-by-concept ) will never work if it needs to access any library. So, indeed that's a problem, but following pointer ownership can greatly reduce the risk. by Alex Vaz, 28.04.2015 17:18
Show remaining 4 comments
1
4

You can use an interceptor before the method call. That is what aspect-oriented programming focus on.

Suppose M1(Object test) is a method and M2 is a method where we apply an aspect before a method call, M2(Object test2). If test2 != null then call M1, otherwise do another thing. It works for all methods with whom you want to apply an aspect for. If you want to apply an aspect for an instance field and constructor you can use AspectJ. Spring can also be the best choice for a method aspect.

03.12.2012 03:15
Comments
are you proposing intercept each method of entire app? by Kurapika, 09.12.2017 20:54
0
5

In Java 8 you can use type T for local-variable/field/method-argument/method-return-type if it never assigned null (and do not check for null) or type Optional<T> if it can be null. Then use method map for processing T -> and method flatMap for processing T -> Optional<R>:

class SomeService {
    @Inject
    private CompanyDao companyDao;

    // return Optional<String>
    public Optional<String> selectCeoCityByCompanyId0(int companyId) {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity);
    }

    // return String + default value
    public String selectCeoCityByCompanyId1(int companyId) {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity)
                .orElse("UNKNOWN");
    }

    // return String + exception
    public String selectCeoCityByCompanyId2(int companyId) throws NoSuchElementException {
        return companyDao.selectById(companyId)
                .map(Company::getCeo)
                .flatMap(Person::getHomeAddress)
                .flatMap(Address::getCity)
                .orElseThrow(NoSuchElementException::new);
    }
}

interface CompanyDao {
    // real situation: no company for such id -> use Optional<Company> 
    Optional<Company> selectById(int id);
}

class Company {
    // company always has ceo -> use Person 
    Person ceo;
    public Person getCeo() {return ceo;}
}

class Person {
    // person always has name -> use String
    String firstName;
    // person can be without address -> use Optional<Address>
    Optional<Address> homeAddress = Optional.empty();

    public String getFirstName() {return firstName;}   
    public Optional<Address> getHomeAddress() {return homeAddress;}
}

class Address {
    //  address always contains country -> use String
    String country;
    //  city field is optional -> use Optional<String>
    Optional<String> city = Optional.empty();

    String getCountry() {return country;}    
    Optional<String> getCity() {return city;}
}
05.07.2016 15:24
0
2

The way to avoid unnecessary null-checks is simple to state:

You need to know which variables can be null, and which cannot, and you need to be confident about which category a given variable fall into.

But, although it can be stated simply enough, achieving it is harder. The key lies in the confident part, because how can you be sure that a variable can't be null?

There are no quick-fix, easy answers to this, but here are some pointers:

  1. Clean code. The most important thing for being able to reason about the behaviour of a piece of code is that it is written in a matter that is easy to understand. Name your variables based on what they represent, name your methods after what they do, apply the Single responsibility principle (the S in SOLID: http://en.wikipedia.org/wiki/SOLID_(object-oriented_design), it means that each piece of code should have a single responsibility, and do this and nothing else). Once your code is clean, it is much easier to reason about it, also across multiple tiers/layers of code. With messy code, trying to understand what a method does might make you forget why you are reading the method in the first place. (Tip: Read "Clean Code" by Robert C. Martin)

  2. Avoid returning null values. If a null value would keep your program from functioning correctly, throw an exception instead (make sure to add the appropriate error-handling.) Cases where returning a null value might be acceptable is for instance trying to fetch an object from the database. In these cases, write code that handles the null values, and make a note behind your ear that here we have something that might return null. Handle returned null values as close to the caller of the method returning null as possible (don't just blindly pass it back up the call-chain.)

  3. Never EVER pass explicit null values as parameters (at least not across classes). If you are ever in a position where passing a null-parameter is the only option, creating a new method that does not have this parameter is the way to go.

  4. Validate your input! Identify the "entry-points" to your application. They can everything from webservices, REST-services, remote EJB classes, controllers, etc. For each method in these entry-points, ask yourself: "Will this method execute correctly if this parameter is null?" If the answer is no, add Validate.notNull(someParam, "Can't function when someParam is null!");. This will throw an IllegalArgumentException if the required parameter is missing. The good thing about this type of validation in the entry-points, is that you can then easily assume in the code being executed from the entry-point, that this variable will never be null! Also, if this fails, being at the entry-point, debugging is made a lot easier than it would if you just got a NullPointerException deep down in your code, since a failure like this can only mean one thing: The client didn't send you all the required information. In most cases you want to validate all input parameters, if you find yourself in a position where you need to allow a lot of null-values, it might be a sign of a badly designed interface, which needs refactoring/additions to suite the needs of the clients.

  5. When working with Collections, return an empty one rather than null!

  6. When working with a database, utilize not null-constraints. In that way, you'll know that a value read from the database cannot be null, and you won't have to check for it.

  7. Structure your code and stick with it. Doing this allows you to make assumptions about the behaviour of the code, for instance if all input to your application is validated, then you can assume that these values will never be null.

  8. If you are not already doing it, write automated tests of your code. By writing tests, you will reason about your code, and you will also become more confident that it does what it's supposed to. Also, automated tests guards you from blunders during refactoring, by letting you know immediatly that this piece of code is not doing what it used to.

You still have to null-check of course, but it can trimmed down to the bare minimum (i.e. the situation where know you might be getting a null-value, instead of everywhere just to be sure.) When it comes to null-checks, i actually prefer to use the ternary operator (but use with care, when you start nesting them they come really messy.)

public String nullSafeToString(final Object o) {
    return o != null ? o.toString() : "null";
}
27.01.2014 20:54
0
3

You can also use the Checker Framework (with JDK 7 and beyond) to statically check for null values. This might solve a lot of problems, but requires running an extra tool that currently only works with OpenJDK AFAIK. https://checkerframework.org/

23.03.2012 20:31
1
-4

Another suggestion is to program defensively - where your classes/functions provide default values that are known and safe, and where null is reserved for true errors/exceptions.

For example, instead of functions that return Strings returning null when there is a problem (say converting a number to a string), have them return an empty String (""). You still have to test the return value before proceeding, but there would be no special cases for exceptions. An additional benefit of this style of programming is that your program will be able to differentiate and respond accordingly between normal operations and exceptions.

16.02.2011 23:14
Comments
-1. That's even worse. Now instead of crashing if you forget to test, your program silently propagates an incorrect value. by Mechanical snail, 17.08.2012 07:05
0
3

With Java 8, you could pass a supplier to a helper method like below,

if(CommonUtil.resolve(()-> a.b().c()).isPresent()) {

}

Above replaces boiler plate code like below,

if(a!=null && a.b()!=null && a.b().c()!=null) {

}

//CommonUtil.java

 public static <T> Optional<T> resolve(Supplier<T> resolver) {
        try {
            T result = resolver.get();
            return Optional.ofNullable(result);
        } catch (NullPointerException var2) {
            return Optional.empty();
        }
    }
07.02.2018 19:00
1
3

Another alternative to the != null check is (if you can't get rid of it design-wise):

Optional.ofNullable(someobject).ifPresent(someobject -> someobject.doCalc());

or

Optional.ofNullable(someobject).ifPresent(SomeClass::doCalc);

With SomeClass being someobject's type.

You can't get a return value back from doCalc() though, so only useful for void methods.

15.05.2019 09:14
Comments
You can get the value by using map combined with get or any of the other methods for getting the value in the Optional, instead of ifPresent. by ThisIsNoZaku, 05.08.2019 20:24
0
3
public class Null {

public static void main(String[] args) {
    String str1 = null;
    String str2 = "";

    if(isNullOrEmpty(str1))
        System.out.println("First string is null or empty.");
    else
        System.out.println("First string is not null or empty.");

    if(isNullOrEmpty(str2))
        System.out.println("Second string is null or empty.");
    else
        System.out.println("Second string is not null or empty.");
}

public static boolean isNullOrEmpty(String str) {
    if(str != null && !str.isEmpty())
        return false;
    return true;
}
}

Output

str1 is null or empty.
str2 is null or empty.

In the above program, we've two strings str1 and str2. str1 contains null value and str2 is an empty string.

We've also created a function isNullOrEmpty() which checks, as the name suggests, whether the string is null or empty. It checks it using a null check using != null and isEmpty() method of string.

In plain terms, if a string isn't a null and isEmpty() returns false, it's not either null or empty. Else, it is.

However, the above program doesn't return empty if a string contains only whitespace characters (spaces). Technically, isEmpty() sees it contains spaces and returns false. For string with spaces, we use the string method trim() to trim out all the leading and trailing whitespace characters.

09.11.2020 07:30