I use x != null to avoid NullPointerException. Is there an alternative?
if (x != null) {
// ...
}
I use x != null to avoid NullPointerException. Is there an alternative?
if (x != null) {
// ...
}
This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indicate something thus requiring the caller to check for nulls.
To put this another way, there are two instances where null checking comes up:
Where null is a valid response in terms of the contract; and
Where it isn't a valid response.
(2) is easy. As of Java 1.7 you can use Objects.requireNonNull(foo). (If you are stuck with a previous version then assertions may be a good alternative.)
"Proper" usage of this method would be like below. The method returns the object passed into it and throws a NullPointerException if the object is null. This means that the returned value is always non-null. The method is primarily intended for validating parameters.
public Foo(Bar bar) {
this.bar = Objects.requireNonNull(bar);
}
It can also be used like an assertion though since it throws an exception if the object is null. In both uses, a message can be added which will be shown in the exception. Below is using it like an assertion and providing a message.
Objects.requireNonNull(someobject, "if someobject is null then something is wrong");
someobject.doCalc();
Generally throwing a specific exception like NullPointerException when a value is null but shouldn't be is favorable to throwing a more general exception like AssertionError. This is the approach the Java library takes; favoring NullPointerException over IllegalArgumentException when an argument is not allowed to be null.
(1) is a little harder. If you have no control over the code you're calling then you're stuck. If null is a valid response, you have to check for it.
If it's code that you do control, however (and this is often the case), then it's a different story. Avoid using nulls as a response. With methods that return collections, it's easy: return empty collections (or arrays) instead of nulls pretty much all the time.
With non-collections it might be harder. Consider this as an example: if you have these interfaces:
public interface Action {
void doSomething();
}
public interface Parser {
Action findAction(String userInput);
}
where Parser takes raw user input and finds something to do, perhaps if you're implementing a command line interface for something. Now you might make the contract that it returns null if there's no appropriate action. That leads the null checking you're talking about.
An alternative solution is to never return null and instead use the Null Object pattern:
public class MyParser implements Parser {
private static Action DO_NOTHING = new Action() {
public void doSomething() { /* do nothing */ }
};
public Action findAction(String userInput) {
// ...
if ( /* we can't find any actions */ ) {
return DO_NOTHING;
}
}
}
Compare:
Parser parser = ParserFactory.getParser();
if (parser == null) {
// now what?
// this would be an example of where null isn't (or shouldn't be) a valid response
}
Action action = parser.findAction(someInput);
if (action == null) {
// do nothing
} else {
action.doSomething();
}
to
ParserFactory.getParser().findAction(someInput).doSomething();
which is a much better design because it leads to more concise code.
That said, perhaps it is entirely appropriate for the findAction() method to throw an Exception with a meaningful error message -- especially in this case where you are relying on user input. It would be much better for the findAction method to throw an Exception than for the calling method to blow up with a simple NullPointerException with no explanation.
try {
ParserFactory.getParser().findAction(someInput).doSomething();
} catch(ActionNotFoundException anfe) {
userConsole.err(anfe.getMessage());
}
Or if you think the try/catch mechanism is too ugly, rather than Do Nothing your default action should provide feedback to the user.
public Action findAction(final String userInput) {
/* Code to return requested Action if found */
return new Action() {
public void doSomething() {
userConsole.err("Action not found: " + userInput);
}
}
}
If you use (or planning to use) a Java IDE like JetBrains IntelliJ IDEA, Eclipse or Netbeans or a tool like findbugs then you can use annotations to solve this problem.
Basically, you've got @Nullable and @NotNull.
You can use in method and parameters, like this:
@NotNull public static String helloWorld() {
return "Hello World";
}
or
@Nullable public static String helloWorld() {
return "Hello World";
}
The second example won't compile (in IntelliJ IDEA).
When you use the first helloWorld() function in another piece of code:
public static void main(String[] args)
{
String result = helloWorld();
if(result != null) {
System.out.println(result);
}
}
Now the IntelliJ IDEA compiler will tell you that the check is useless, since the helloWorld() function won't return null, ever.
Using parameter
void someMethod(@NotNull someParameter) { }
if you write something like:
someMethod(null);
This won't compile.
Last example using @Nullable
@Nullable iWantToDestroyEverything() { return null; }
Doing this
iWantToDestroyEverything().something();
And you can be sure that this won't happen. :)
It's a nice way to let the compiler check something more than it usually does and to enforce your contracts to be stronger. Unfortunately, it's not supported by all the compilers.
In IntelliJ IDEA 10.5 and on, they added support for any other @Nullable @NotNull implementations.
See blog post More flexible and configurable @Nullable/@NotNull annotations.
If 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.
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.
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.
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 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:
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.
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) ) {
// ...
}
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");
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
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.
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);.
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();
Ultimately, the only way to completely solve this problem is by using a different programming language:
nil, and absolutely nothing will happen. This makes most null checks unnecessary, but it can make errors much harder to diagnose.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.
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
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!
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
All in all to avoid statement
if (object != null) {
....
}
since java 7 you can use Objects methods:
Objects.isNull(object)
Objects.nonNull(object)
Objects.requireNonNull(object)
Objects.equals(object1, object2)
since java 8 you can use Optional class (when to use)
object.ifPresent(obj -> ...); java 8
object.ifPresentOrElse(obj -> ..., () -> ...); java 9
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);
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
public static Object defaultIfNull(Object object, Object defaultValue)
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.
public static boolean isNull(Object obj)
Returns true if the provided reference is null otherwise returns false.
Since Java 1.8
public static boolean nonNull(Object obj)
Returns true if the provided reference is non-null otherwise returns false.
Since Java 1.8
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
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
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.
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
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
}
}
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.
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/
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();
}
}
There has a good way to check the null value from JDK. It is Optional.java that has a sea of methods to resolve these problems. Such as follow:
/**
* Returns an {@code Optional} describing the specified value, if non-null,
* otherwise returns an empty {@code Optional}.
*
* @param <T> the class of the value
* @param value the possibly-null value to describe
* @return an {@code Optional} with a present value if the specified value
* is non-null, otherwise an empty {@code Optional}
*/
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
/**
* Return {@code true} if there is a value present, otherwise {@code false}.
*
* @return {@code true} if there is a value present, otherwise {@code false}
*/
public boolean isPresent() {
return value != null;
}
/**
* If a value is present, invoke the specified consumer with the value,
* otherwise do nothing.
*
* @param consumer block to be executed if a value is present
* @throws NullPointerException if value is present and {@code consumer} is
* null
*/
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
It is really, really useful to help javer.
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.
Objects.isNull(null)
If you are using Java8 then you can try this code.
Try using below code if you are not using Java8
Object ob=null;
if(ob==null){ **do something}
Functional approach may help to wrap the repetitive null checks and execute anonymous code like the below sample.
BiConsumer<Object, Consumer<Object>> consumeIfPresent = (s,f) ->{
if(s!=null) {
f.accept(s);
}
};
consumeIfPresent.accept(null, (s)-> System.out.println(s) );
consumeIfPresent.accept("test", (s)-> System.out.println(s));
BiFunction<Object, Function<Object,Object>,Object> executeIfPresent = (a,b) ->{
if(a!=null) {
return b.apply(a);
}
return null;
};
executeIfPresent.apply(null, (s)-> {System.out.println(s);return s;} );
executeIfPresent.apply("test", (s)-> {System.out.println(s);return s;} );
You can make one generic Method for object and string so that you can use it through out in your application- This could help you and your colleagues : Create a class eg. StringUtilities and add the method eg. getNullString
public static String getNullString(Object someobject)
{
if(null==someobject )
return null;
else if(someobject.getClass().isInstance("") &&
(((String)someobject).trim().equalsIgnoreCase("null")||
((String)someobject).trim().equalsIgnoreCase("")))
return null;
else if(someobject.getClass().isInstance(""))
return (String)someobject;
else
return someobject.toString().trim();
}
And simply call this method as,
if (StringUtilities.getNullString(someobject) != null)
{
//Do something
}
The best way to avoid Null Checks in Java, is to properly handle and use exceptions. Null Checks in my experience have become more common and required as you move closer to the front-end, because it's closer to the user who may supply invalid information through the UI (such as, no value, being submitted for a field).
One may argue that you should be able to control what the UI is doing, lest you forget most UI is done through a third party library of some kind, which for example, may return either NULL or an Empty String for a blank text box, depending on the situation or the library.
You can combine the two like this:
try
{
myvar = get_user_supplied_value();
if (myvar == null || myvar.length() == 0) { alert_the_user_somehow(); return; };
process_user_input(myvar);
} catch (Exception ex) {
handle_exception(ex);
}
Another approach people take is to say:
if (myvar && myvar.length() > 0) { };
You could also throw an exception (which is what I prefer)
if (myvar == null || myvar.length() == 0) {
throw new Exception("You must supply a name!");
};
But that's up to you.
Personally, I would either go with jim-nelson's answer or if I do find a null check is convenient for a specific context I would incorporate lombok into my project and use the @NonNull annotation.
Example:
import lombok.NonNull;
public class NonNullExample extends Something {
private String name;
public NonNullExample(@NonNull Person person) {
super("Hello");
this.name = person.getName();
}
}
Even the @NonNull preface mention:
Null object pattern can be used as a solution for this problem. For that, the class of the someObject should be modified.
public abstract class SomeObject {
public abstract boolean isNil();
}
public class NullObject extends SomeObject {
@Override
public boolean isNil() {
return true;
}
}
public class RealObject extends SomeObject {
@Override
public boolean isNil() {
return false;
}
}
Now istead of checking,
if (someobject != null) {
someobject.doCalc();
}
We can use,
if (!someObject.isNil()) {
someobject.doCalc();
}
Reference : https://www.tutorialspoint.com/design_pattern/null_object_pattern.htm
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.