Best way to check for null values in Java? - java

Before calling a function of an object, I need to check if the object is null, to avoid throwing a NullPointerException.
What is the best way to go about this? I've considered these methods.
Which one is the best programming practice for Java?
// Method 1
if (foo != null) {
if (foo.bar()) {
etc...
}
}
// Method 2
if (foo != null ? foo.bar() : false) {
etc...
}
// Method 3
try {
if (foo.bar()) {
etc...
}
} catch (NullPointerException e) {
}
// Method 4 -- Would this work, or would it still call foo.bar()?
if (foo != null && foo.bar()) {
etc...
}

Method 4 is best.
if(foo != null && foo.bar()) {
someStuff();
}
will use short-circuit evaluation, meaning it ends if the first condition of a logical AND is false.

The last and the best one. i.e LOGICAL AND
if (foo != null && foo.bar()) {
etc...
}
Because in logical &&
it is not necessary to know what the right hand side is, the result must be false
Prefer to read :Java logical operator short-circuiting

Since java 8 you can use Objects.nonNull(Object obj)
if(nonNull(foo)){
//
}

Do not catch NullPointerException. That is a bad practice. It is better to ensure that the value is not null.
Method #4 will work for you. It will not evaluate the second condition, because Java has short-circuiting (i.e., subsequent conditions will not be evaluated if they do not change the end-result of the boolean expression). In this case, if the first expression of a logical AND evaluates to false, subsequent expressions do not need to be evaluated.

Method 4 is far and away the best as it clearly indicates what will happen and uses the minimum of code.
Method 3 is just wrong on every level. You know the item may be null so it's not an exceptional situation it's something you should check for.
Method 2 is just making it more complicated than it needs to be.
Method 1 is just method 4 with an extra line of code.

In Java 7, you can use Objects.requireNonNull().
Add an import of Objects class from java.util.
public class FooClass {
//...
public void acceptFoo(Foo obj) {
//If obj is null, NPE is thrown
Objects.requireNonNull(obj).bar(); //or better requireNonNull(obj, "obj is null");
}
//...
}

As others have said #4 is the best method when not using a library method. However you should always put null on the left side of the comparison to ensure you don't accidentally assign null to foo in case of typo. In that case the compiler will catch the mistake.
// You meant to do this
if(foo != null){
// But you made a typo like this which will always evaluate to true
if(foo = null)
// Do the comparison in this way
if(null != foo)
// So if you make the mistake in this way the compiler will catch it
if(null = foo){
// obviously the typo is less obvious when doing an equality comparison but it's a good habit either way
if(foo == null){
if(foo = null){

I would say method 4 is the most general idiom from the code that I've looked at. But this always feels a bit smelly to me. It assumes foo == null is the same as foo.bar() == false.
That doesn't always feel right to me.

Method 4 is my preferred method. The short circuit of the && operator makes the code the most readable. Method 3, Catching NullPointerException, is frowned upon most of the time when a simple null check would suffice.

Simple one line Code to check for null :
namVar == null ? codTdoForNul() : codTdoForFul();

Update
I created a java library(Maven Dependency) for the java developers to remove this NullPointerException Hell from their code.
Check out my repository.
NullUtil Repository
Generic Method to handle Null Values in Java
<script src="https://gist.github.com/rcvaram/f1a1b89193baa1de39121386d5f865bc.js"></script>
If that object is not null we are going to do the following things.
a. We can mutate the object (I)
b. We can return something(O) as output instead of mutating the object (I)
c. we can do both
In this case, We need to pass a function which needs to take the input param(I) which is our object If we take it like that, then we can mutate that object if we want. and also that function may be something (O).
If an object is null then we are going to do the following things
a. We may throw an exception in a customized way
b. We may return something.
In this case, the object is null so we need to supply the value or we may need to throw an exception.
I take two examples.
If I want to execute trim in a String then that string should not be null. In that case, we have to additionally check the null value otherwise we will get NullPointerException
public String trimValue(String s){
return s == null ? null : s.trim();
}
Another function which I want to set a new value to object if that object is not null otherwise I want to throw a runtime exception.
public void setTeacherAge(Teacher teacher, int age){
if (teacher != null){
teacher.setAge(age);
} else{
throw new RuntimeException("teacher is null")
}
}
With my Explanation, I have created a generic method that takes the value(value may be null), a function that will execute if the object is not null and another supplier function that will execute if the object is null.
GenericFunction
public <I, O> O setNullCheckExecutor(I value, Function<I, O> nonNullExecutor, Supplier<O> nullExecutor) {
return value != null ? nonNullExecutor.apply(value) : nullExecutor.get();
}
So after having this generic function, we can do as follow for the example methods
1.
//To Trim a value
String trimmedValue = setNullCheckExecutor(value, String::trim, () -> null);
Here, the nonNullExecutor Function is trim the value (Method Reference is used). nullExecutorFunction is will return null since It is an identity function.
2.
// mutate the object if not null otherwise throw a custom message runtime exception instead of NullPointerException
setNullCheckExecutor(teacher, teacher -> {
teacher.setAge(19);
return null;
}, () -> {
throw new RuntimeException("Teacher is null");
});

Correction: This is only true for C/C++ not for Java, sorry.
If at all you going to check with double equal "==" then check null with object ref like
if(null == obj)
instead of
if(obj == null)
because if you mistype single equal if(obj = null) it will return true (assigning object returns success (which is 'true' in value).

You also can use ObjectUtils.isNotEmpty() to check if an Object is not empty and not null.

If you control the API being called, consider using Guava's Optional class
More info here. Change your method to return an Optional<Boolean> instead of a Boolean.
This informs the calling code that it must account for the possibility of null, by calling one of the handy methods in Optional

if you do not have an access to the commons apache library, the following probably will work ok
if(null != foo && foo.bar()) {
//do something
}

Your last proposal is the best.
if (foo != null && foo.bar()) {
etc...
}
Because:
It is easier to read.
It is safe : foo.bar() will never be executed if foo == null.
It prevents from bad practice such as catching NullPointerExceptions (most of the time due to a bug in your code)
It should execute as fast or even faster than other methods (even though I think it should be almost impossible to notice it).

We can use Object.requireNonNull static method of Object class. Implementation is below
public void someMethod(SomeClass obj) {
Objects.requireNonNull(obj, "Validation error, obj cannot be null");
}

public <T, U> U defaultGet(T supplier, Function<T, U> mapper, U defaultValue) {
return Optional.ofNullable(supplier).map(mapper).orElse(defaultValue);
}
You can create this function if you prefer function programming

Allot of times I look for null when processing a function -
public static void doSomething(Object nullOrNestedObject) {
if (nullOrNestedObject == null || nullOrNestedObject.getNestedObject()) {
log.warn("Invalid argument !" );
return;
// Or throw an exception
// throw new IllegalArgumentException("Invalid argument!");
}
nullOrNestedObject.getNestedObject().process()
... // Do other function stuff
}
That way if it is null it just stops execution early, and you don't have to nest all of your logic in an if.

Related

How to check if a java method returns null without having to run it twice

I have this situation many times in my code,
I have a method for example such as:
private Object doSomething(){
//Do something
doSomething ? return Object : return null;
}
This is just an example, then in the main body of my code I need to check that this doesn't return null before I do something else. For example:
if(doSomething() != null){
Object object = doSomething();
From a performance perspective this method is being asked to run twice, once to check it doesn't return null and next to assign the new variable as long as it returns a valid object.
Is there a way to develop this code where this double running doesn't have to take place. Bearing in mind that the check to make sure the object is valid is important in the code.
Just reverse the process. First assign the result of that call to a variable, then check if the variable is null.
Object object = doSomething();
if (object != null) {
// do whatever with object
} else {
// do something else
}
It is worth noting that the problem with multiple calls to doSomething may not only be a performance penalty. It could also be a problem if:
doSomething has side effects, for example if it inserts a row in a database, in which case calling it twice will insert two rows.
doSomething depends on some external state which may change between invocations.
Consider using Optional rather than returning null (introduced with Java 8).
public Optional<Object> doSomething() {
return Optional.ofNullable(someData);
}
When invoked, you have an Optional reference that may (or may not) have contents.
Optional<Object> maybeSomething = doSomething();
if (maybeSomething.isPresent()) {
Object someData = maybeSomething.get();
System.out.println("SomeData = "+someData);
}
Optional blends well with lambda so you could rewrite that as..
Optional<Object> maybeSomething = doSomething();
maybeSomething.ifPresent(someData -> System.out.println("SomeData = " + someData);
or, if you don't need to do more work with someData you could even do
doSomething().ifPresent(someData -> System.out.println("SomeData = " + someData);

Getter on nested objects without having NullPointerException [duplicate]

A web service returns a huge XML and I need to access deeply nested fields of it. For example:
return wsObject.getFoo().getBar().getBaz().getInt()
The problem is that getFoo(), getBar(), getBaz() may all return null.
However, if I check for null in all cases, the code becomes very verbose and hard to read. Moreover, I may miss the checks for some of the fields.
if (wsObject.getFoo() == null) return -1;
if (wsObject.getFoo().getBar() == null) return -1;
// maybe also do something with wsObject.getFoo().getBar()
if (wsObject.getFoo().getBar().getBaz() == null) return -1;
return wsObject.getFoo().getBar().getBaz().getInt();
Is it acceptable to write
try {
return wsObject.getFoo().getBar().getBaz().getInt();
} catch (NullPointerException ignored) {
return -1;
}
or would that be considered an antipattern?
Catching NullPointerException is a really problematic thing to do since they can happen almost anywhere. It's very easy to get one from a bug, catch it by accident and continue as if everything is normal, thus hiding a real problem. It's so tricky to deal with so it's best to avoid altogether. (For example, think about auto-unboxing of a null Integer.)
I suggest that you use the Optional class instead. This is often the best approach when you want to work with values that are either present or absent.
Using that you could write your code like this:
public Optional<Integer> m(Ws wsObject) {
return Optional.ofNullable(wsObject.getFoo()) // Here you get Optional.empty() if the Foo is null
.map(f -> f.getBar()) // Here you transform the optional or get empty if the Bar is null
.map(b -> b.getBaz())
.map(b -> b.getInt());
// Add this if you want to return null instead of an empty optional if any is null
// .orElse(null);
// Or this if you want to throw an exception instead
// .orElseThrow(SomeApplicationException::new);
}
Why optional?
Using Optionals instead of null for values that might be absent makes that fact very visible and clear to readers, and the type system will make sure you don't accidentally forget about it.
You also get access to methods for working with such values more conveniently, like map and orElse.
Is absence valid or error?
But also think about if it is a valid result for the intermediate methods to return null or if that is a sign of an error. If it is always an error then it's probably better throw an exception than to return a special value, or for the intermediate methods themselves to throw an exception.
Maybe more optionals?
If on the other hand absent values from the intermediate methods are valid, maybe you can switch to Optionals for them also?
Then you could use them like this:
public Optional<Integer> mo(Ws wsObject) {
return wsObject.getFoo()
.flatMap(f -> f.getBar())
.flatMap(b -> b.getBaz())
.flatMap(b -> b.getInt());
}
Why not optional?
The only reason I can think of for not using Optional is if this is in a really performance critical part of the code, and if garbage collection overhead turns out to be a problem. This is because a few Optional objects are allocated each time the code is executed, and the VM might not be able to optimize those away. In that case your original if-tests might be better.
I suggest considering Objects.requireNonNull(T obj, String message). You might build chains with a detailed message for each exception, like
requireNonNull(requireNonNull(requireNonNull(
wsObject, "wsObject is null")
.getFoo(), "getFoo() is null")
.getBar(), "getBar() is null");
I would suggest you not to use special return-values, like -1. That's not a Java style. Java has designed the mechanism of exceptions to avoid this old-fashioned way which came from the C language.
Throwing NullPointerException is not the best option too. You could provide your own exception (making it checked to guarantee that it will be handled by a user or unchecked to process it in an easier way) or use a specific exception from XML parser you are using.
Assuming the class structure is indeed out of our control, as seems to be the case, I think catching the NPE as suggested in the question is indeed a reasonable solution, unless performance is a major concern. One small improvement might be to wrap the throw/catch logic to avoid clutter:
static <T> T get(Supplier<T> supplier, T defaultValue) {
try {
return supplier.get();
} catch (NullPointerException e) {
return defaultValue;
}
}
Now you can simply do:
return get(() -> wsObject.getFoo().getBar().getBaz().getInt(), -1);
As already pointed out by Tom in the comment,
Following statement disobeys the Law of Demeter,
wsObject.getFoo().getBar().getBaz().getInt()
What you want is int and you can get it from Foo. Law of Demeter says, never talk to the strangers. For your case you can hide the actual implementation under the hood of Foo and Bar.
Now, you can create method in Foo to fetch int from Baz. Ultimately, Foo will have Bar and in Bar we can access Int without exposing Baz directly to Foo. So, null checks are probably divided to different classes and only required attributes will be shared among the classes.
My answer goes almost in the same line as #janki, but I would like to modify the code snippet slightly as below:
if (wsObject.getFoo() != null && wsObject.getFoo().getBar() != null && wsObject.getFoo().getBar().getBaz() != null)
return wsObject.getFoo().getBar().getBaz().getInt();
else
return something or throw exception;
You can add a null check for wsObject as well, if there's any chance of that object being null.
You say that some methods "may return null" but do not say in what circumstances they return null. You say you catch the NullPointerException but you do not say why you catch it. This lack of information suggests you do not have a clear understanding of what exceptions are for and why they are superior to the alternative.
Consider a class method that is meant to perform an action, but the method can not guarantee it will perform the action, because of circumstances beyond its control (which is in fact the case for all methods in Java). We call that method and it returns. The code that calls that method needs to know whether it was successful. How can it know? How can it be structured to cope with the two possibilities, of success or failure?
Using exceptions, we can write methods that have success as a post condition. If the method returns, it was successful. If it throws an exception, it had failed. This is a big win for clarity. We can write code that clearly processes the normal, success case, and move all the error handling code into catch clauses. It often transpires that the details of how or why a method was unsuccessful are not important to the caller, so the same catch clause can be used for handling several types of failure. And it often happens that a method does not need to catch exceptions at all, but can just allow them to propagate to its caller. Exceptions due to program bugs are in that latter class; few methods can react appropriately when there is a bug.
So, those methods that return null.
Does a null value indicate a bug in your code? If it does, you should not be catching the exception at all. And your code should not be trying to second guess itself. Just write what is clear and concise on the assumption that it will work. Is a chain of method calls clear and concise? Then just use them.
Does a null value indicate invalid input to your program? If it does, a NullPointerException is not an appropriate exception to throw, because conventionally it is reserved for indicating bugs. You probably want to throw a custom exception derived from IllegalArgumentException (if you want an unchecked exception) or IOException (if you want a checked exception). Is your program required to provide detailed syntax error messages when there is invalid input? If so, checking each method for a null return value then throwing an appropriate diagnostic exception is the only thing you can do. If your program need not provide detailed diagnostics, chaining the method calls together, catching any NullPointerException and then throwing your custom exception is clearest and most concise.
One of the answers claims that the chained method calls violate the Law of Demeter and thus are bad. That claim is mistaken.
When it comes to program design, there are not really any absolute rules about what is good and what is bad. There are only heuristics: rules that are right much (even almost all) of the time. Part of the skill of programming is knowing when it is OK to break those kinds of rules. So a terse assertion that "this is against rule X" is not really an answer at all. Is this one of the situations where the rule should be broken?
The Law of Demeter is really a rule about API or class interface design. When designing classes, it is useful to have a hierarchy of abstractions. You have low level classes that uses the language primitives to directly perform operations and represent objects in an abstraction that is higher level than the language primitives. You have medium level classes that delegate to the low level classes, and implement operations and representations at a higher level than the low level classes. You have high level classes that delegate to the medium level classes, and implement still higher level operations and abstractions. (I've talked about just three levels of abstraction here, but more are possible). This allows your code to express itself in terms of appropriate abstractions at each level, thereby hiding complexity. The rationale for the Law of Demeter is that if you have a chain of method calls, that suggests you have a high level class reaching in through a medium level class to deal directly with low level details, and therefore that your medium level class has not provided a medium-level abstract operation that the high level class needs. But it seems that is not the situation you have here: you did not design the classes in the chain of method calls, they are the result of some auto-generated XML serialization code (right?), and the chain of calls is not descending through an abstraction hierarchy because the des-serialized XML is all at the same level of the abstraction hierarchy (right?)?
As others have said, respecting the Law of Demeter is definitely part of the solution. Another part, wherever possible, is to change those chained methods so they cannot return null. You can avoid returning null by instead returning an empty String, an empty Collection, or some other dummy object that means or does whatever the caller would do with null.
To improve readability, you may want to use multiple variables, like
Foo theFoo;
Bar theBar;
Baz theBaz;
theFoo = wsObject.getFoo();
if ( theFoo == null ) {
// Exit.
}
theBar = theFoo.getBar();
if ( theBar == null ) {
// Exit.
}
theBaz = theBar.getBaz();
if ( theBaz == null ) {
// Exit.
}
return theBaz.getInt();
Don't catch NullPointerException. You don't know where it is coming from (I know it is not probable in your case but maybe something else threw it) and it is slow.
You want to access the specified field and for this every other field has to be not null. This is a perfect valid reason to check every field. I would probably check it in one if and then create a method for readability. As others pointed out already returning -1 is very oldschool but I don't know if you have a reason for it or not (e.g. talking to another system).
public int callService() {
...
if(isValid(wsObject)){
return wsObject.getFoo().getBar().getBaz().getInt();
}
return -1;
}
public boolean isValid(WsObject wsObject) {
if(wsObject.getFoo() != null &&
wsObject.getFoo().getBar() != null &&
wsObject.getFoo().getBar().getBaz() != null) {
return true;
}
return false;
}
Edit: It is debatable if it's disobeyes the Law Of Demeter since the WsObject is probably only a data structure (check https://stackoverflow.com/a/26021695/1528880).
If you don't want to refactor the code and you can use Java 8, it is possible to use Method references.
A simple demo first (excuse the static inner classes)
public class JavaApplication14
{
static class Baz
{
private final int _int;
public Baz(int value){ _int = value; }
public int getInt(){ return _int; }
}
static class Bar
{
private final Baz _baz;
public Bar(Baz baz){ _baz = baz; }
public Baz getBar(){ return _baz; }
}
static class Foo
{
private final Bar _bar;
public Foo(Bar bar){ _bar = bar; }
public Bar getBar(){ return _bar; }
}
static class WSObject
{
private final Foo _foo;
public WSObject(Foo foo){ _foo = foo; }
public Foo getFoo(){ return _foo; }
}
interface Getter<T, R>
{
R get(T value);
}
static class GetterResult<R>
{
public R result;
public int lastIndex;
}
/**
* #param args the command line arguments
*/
public static void main(String[] args)
{
WSObject wsObject = new WSObject(new Foo(new Bar(new Baz(241))));
WSObject wsObjectNull = new WSObject(new Foo(null));
GetterResult<Integer> intResult
= getterChain(wsObject, WSObject::getFoo, Foo::getBar, Bar::getBar, Baz::getInt);
GetterResult<Integer> intResult2
= getterChain(wsObjectNull, WSObject::getFoo, Foo::getBar, Bar::getBar, Baz::getInt);
System.out.println(intResult.result);
System.out.println(intResult.lastIndex);
System.out.println();
System.out.println(intResult2.result);
System.out.println(intResult2.lastIndex);
// TODO code application logic here
}
public static <R, V1, V2, V3, V4> GetterResult<R>
getterChain(V1 value, Getter<V1, V2> g1, Getter<V2, V3> g2, Getter<V3, V4> g3, Getter<V4, R> g4)
{
GetterResult result = new GetterResult<>();
Object tmp = value;
if (tmp == null)
return result;
tmp = g1.get((V1)tmp);
result.lastIndex++;
if (tmp == null)
return result;
tmp = g2.get((V2)tmp);
result.lastIndex++;
if (tmp == null)
return result;
tmp = g3.get((V3)tmp);
result.lastIndex++;
if (tmp == null)
return result;
tmp = g4.get((V4)tmp);
result.lastIndex++;
result.result = (R)tmp;
return result;
}
}
Output
241
4
null
2
The interface Getter is just a functional interface, you may use any equivalent.
GetterResult class, accessors stripped out for clarity, hold the result of the getter chain, if any, or the index of the last getter called.
The method getterChain is a simple, boilerplate piece of code, that can be generated automatically (or manually when needed).
I structured the code so that the repeating block is self evident.
This is not a perfect solution as you still need to define one overload of getterChain per number of getters.
I would refactor the code instead, but if can't and you find your self using long getter chains often you may consider building a class with the overloads that take from 2 to, say, 10, getters.
I'd like to add an answer which focus on the meaning of the error. Null exception in itself doesn't provide any meaning full error. So I'd advise to avoid dealing with them directly.
There is a thousands cases where your code can go wrong: cannot connect to database, IO Exception, Network error... If you deal with them one by one (like the null check here), it would be too much of a hassle.
In the code:
wsObject.getFoo().getBar().getBaz().getInt();
Even when you know which field is null, you have no idea about what goes wrong. Maybe Bar is null, but is it expected? Or is it a data error? Think about people who read your code
Like in xenteros's answer, I'd propose using custom unchecked exception. For example, in this situation: Foo can be null (valid data), but Bar and Baz should never be null (invalid data)
The code can be re-written:
void myFunction()
{
try
{
if (wsObject.getFoo() == null)
{
throw new FooNotExistException();
}
return wsObject.getFoo().getBar().getBaz().getInt();
}
catch (Exception ex)
{
log.error(ex.Message, ex); // Write log to track whatever exception happening
throw new OperationFailedException("The requested operation failed")
}
}
void Main()
{
try
{
myFunction();
}
catch(FooNotExistException)
{
// Show error: "Your foo does not exist, please check"
}
catch(OperationFailedException)
{
// Show error: "Operation failed, please contact our support"
}
}
NullPointerException is a run-time exception, so generally speaking is not recommended to catch it, but to avoid it.
You will have to catch the exception wherever you want to call the method (or it will propagate up the stack). Nevertheless, if in your case you can keep working with that result with value -1 and you are sure that it won't propagate because you are not using any of the "pieces" that may be null, then it seems right to me to catch it
Edit:
I agree with the later answer from #xenteros, it wil be better to launch your own exception instead returning -1 you can call it InvalidXMLException for instance.
Have been following this post since yesterday.
I have been commenting/voting the comments which says, catching NPE is bad. Here is why I have been doing that.
package com.todelete;
public class Test {
public static void main(String[] args) {
Address address = new Address();
address.setSomeCrap(null);
Person person = new Person();
person.setAddress(address);
long startTime = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
try {
System.out.println(person.getAddress().getSomeCrap().getCrap());
} catch (NullPointerException npe) {
}
}
long endTime = System.currentTimeMillis();
System.out.println((endTime - startTime) / 1000F);
long startTime1 = System.currentTimeMillis();
for (int i = 0; i < 1000000; i++) {
if (person != null) {
Address address1 = person.getAddress();
if (address1 != null) {
SomeCrap someCrap2 = address1.getSomeCrap();
if (someCrap2 != null) {
System.out.println(someCrap2.getCrap());
}
}
}
}
long endTime1 = System.currentTimeMillis();
System.out.println((endTime1 - startTime1) / 1000F);
}
}
public class Person {
private Address address;
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
package com.todelete;
public class Address {
private SomeCrap someCrap;
public SomeCrap getSomeCrap() {
return someCrap;
}
public void setSomeCrap(SomeCrap someCrap) {
this.someCrap = someCrap;
}
}
package com.todelete;
public class SomeCrap {
private String crap;
public String getCrap() {
return crap;
}
public void setCrap(String crap) {
this.crap = crap;
}
}
Output
3.216
0.002
I see a clear winner here. Having if checks is way too less expensive than catch an exception. I have seen that Java-8 way of doing. Considering that 70% of the current applications still run on Java-7 I am adding this answer.
Bottom Line For any mission critical applications, handling NPE is costly.
If efficiency is an issue then the 'catch' option should be considered.
If 'catch' cannot be used because it would propagate (as mentioned by 'SCouto') then use local variables to avoid multiple calls to methods getFoo(), getBar() and getBaz().
It's worth considering to create your own Exception. Let's call it MyOperationFailedException. You can throw it instead returning a value. The result will be the same - you'll quit the function, but you won't return hard-coded value -1 which is Java anti-pattern. In Java we use Exceptions.
try {
return wsObject.getFoo().getBar().getBaz().getInt();
} catch (NullPointerException ignored) {
throw new MyOperationFailedException();
}
EDIT:
According to the discussion in comments let me add something to my previous thoughts. In this code there are two possibilities. One is that you accept null and the other one is, that it is an error.
If it's an error and it occurs, You can debug your code using other structures for debugging purposes when breakpoints aren't enough.
If it's acceptable, you don't care about where this null appeared. If you do, you definitely shouldn't chain those requests.
The method you have is lengthy, but very readable. If I were a new developer coming to your code base I could see what you were doing fairly quickly. Most of the other answers (including catching the exception) don't seem to be making things more readable and some are making it less readable in my opinion.
Given that you likely don't have control over the generated source and assuming you truly just need to access a few deeply nested fields here and there then I would recommend wrapping each deeply nested access with a method.
private int getFooBarBazInt() {
if (wsObject.getFoo() == null) return -1;
if (wsObject.getFoo().getBar() == null) return -1;
if (wsObject.getFoo().getBar().getBaz() == null) return -1;
return wsObject.getFoo().getBar().getBaz().getInt();
}
If you find yourself writing a lot of these methods or if you find yourself tempted to make these public static methods then I would create a separate object model, nested how you would like, with only the fields you care about, and convert from the web services object model to your object model.
When you are communicating with a remote web service it is very typical to have a "remote domain" and an "application domain" and switch between the two. The remote domain is often limited by the web protocol (for example, you can't send helper methods back and forth in a pure RESTful service and deeply nested object models are common to avoid multiple API calls) and so not ideal for direct use in your client.
For example:
public static class MyFoo {
private int barBazInt;
public MyFoo(Foo foo) {
this.barBazInt = parseBarBazInt();
}
public int getBarBazInt() {
return barBazInt;
}
private int parseFooBarBazInt(Foo foo) {
if (foo() == null) return -1;
if (foo().getBar() == null) return -1;
if (foo().getBar().getBaz() == null) return -1;
return foo().getBar().getBaz().getInt();
}
}
return wsObject.getFooBarBazInt();
by applying the the Law of Demeter,
class WsObject
{
FooObject foo;
..
Integer getFooBarBazInt()
{
if(foo != null) return foo.getBarBazInt();
else return null;
}
}
class FooObject
{
BarObject bar;
..
Integer getBarBazInt()
{
if(bar != null) return bar.getBazInt();
else return null;
}
}
class BarObject
{
BazObject baz;
..
Integer getBazInt()
{
if(baz != null) return baz.getInt();
else return null;
}
}
class BazObject
{
Integer myInt;
..
Integer getInt()
{
return myInt;
}
}
Giving answer which seems different from all others.
I recommend you to check for NULL in ifs.
Reason :
We should not leave a single chance for our program to be crashed.
NullPointer is generated by system. The behaviour of System
generated exceptions can not be predicted. You should not leave your
program in the hands of System when you already have a way of handling
it by your own. And put the Exception handling mechanism for the extra safety.!!
For making your code easy to read try this for checking the conditions :
if (wsObject.getFoo() == null || wsObject.getFoo().getBar() == null || wsObject.getFoo().getBar().getBaz() == null)
return -1;
else
return wsObject.getFoo().getBar().getBaz().getInt();
EDIT :
Here you need to store these values wsObject.getFoo(),
wsObject.getFoo().getBar(), wsObject.getFoo().getBar().getBaz() in
some variables. I am not doing it because i don't know the return
types of that functions.
Any suggestions will be appreciated..!!
I wrote a class called Snag which lets you define a path to navigate through a tree of objects. Here is an example of its use:
Snag<Car, String> ENGINE_NAME = Snag.createForAndReturn(Car.class, String.class).toGet("engine.name").andReturnNullIfMissing();
Meaning that the instance ENGINE_NAME would effectively call Car?.getEngine()?.getName() on the instance passed to it, and return null if any reference returned null:
final String name = ENGINE_NAME.get(firstCar);
It's not published on Maven but if anyone finds this useful it's here (with no warranty of course!)
It's a bit basic but it seems to do the job. Obviously it's more obsolete with more recent versions of Java and other JVM languages that support safe navigation or Optional.

Is using the order of evaluation to check for null values bad practice?

If I wish to perform two checks on a string, that it is not null, and that it is not 0 length, I could do this-
if(string != null) {
if(string.length() > 0) {
//Do something
}
}
Or I could do this
if(string != null && string.length() > 0) {
//Do something
}
As the first check is executed first, the second comparison doesn't happen and a NullPointerException isn't thrown.
Is the second method guaranteed to work in all cases? And if so, would it be considered bad practice to use it?
No, it is perfectly fine and guaranteed to work in all cases.
Reference from Java specification: https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.7
The one worth mentioning here: as you write such checks very often, it is advisable to put them into some dedicated helper method; such as:
static boolean doesStringContentContent(String value) {
or something alike.
And from an "improved" readability perspective, you might prefer coding that like
if (value == null) return false;
if (value.isEmpty()) return false;
return true;
But that doesn't matter too much - the important part is that you should not start copying around this check.
And finally, the one other possibility would to not return a boolean, but to have a
void checkStringHasContent(String value) {
which could throw a NullPointerException resp. some other thingy for an empty string.
you are using && (and) operator in second expression. and nested if condition in first expression. in both cases you will get same result. because &&(and) operator execute second condition if only if first condition is true.
basically you are doing same thing in different manner.

Check if last getter in method chain is not null

In code we have got a lot of chain methods, for example obj.getA().getB().getC().getD(). I want to create helper class which will check if method getD() isn't null, but before that I need to check all previous getters. I can do it in this way:
try {
obj.getA().getB().getC().getD();
}
catch (NullPointerException e) {
// some getter is null
}
or (which is "silly")
if (obj!null && obj.getA()!=null && obj.getA().getB()!=null && ...) {
obj.getA().getB().getC().getD();
}
else {
// some getter is null
}
I don't want to check it every time using try{} catch() in my code. What is the best solution for this purpose?
I think that the best will be:
obj.getA().getB().getC().getD().isNull() - for this purpose I will need to change all of my getters, for example implement some interface which contains isNull() method.
NullObjectHelper.isNull(obj.getA().getB().getC().getD()); - this will be the best (I think so) but how to implement this?
As of Java 8 you can use methods like Optional.isPresent and Optional.orElse to handle null in getter chains:
boolean dNotNull = Optional.ofNullable(obj)
.map(Obj::getA)
.map(A::getB)
.map(B::getC)
.map(C::getD)
.isPresent();
While this is preferable to catching NullPointerException the downside of this approach is the object allocations for Optional instances.
It is possible to write your own static methods that perform similar operations without this overhead:
boolean dNotNull = Nulls.isNotNull(obj, Obj::getA, A::getB, B::getC, C::getD);
For a sample implementation, see the Nullifier type here.
No approach is likely to have greater runtime efficiency than nested if-not-null checks.
You can achieve the desired result with Option pattern. This enforces you to change a method signature, but basically if your method returns some type T, it guarantees it has some non-null value, and if it returnsOption<T> it means it either has value T, or null.
Java 7 had some feature called null safety, but it was removed from the final release. You could do:
obj?.getA()?.getB()?.getC()?.getD()
Moreover, Java 8 will add a feature called Optional so you would do it safely.
In fact, if you really want to use that now, try Null Object pattern. It means that instead of returning plain null you can return some sort of default value, which won't trigger NullPointerException. Though, you need add some changes to your getters
class Object {
A getA() {
// ...
return a == null ? A.NULL : a;
}
}
class A {
static A NULL = new A(); // some default behaviour
B getB() {
if (this == NULL) return B.NULL;
// ...
return b == null ? B.NULL : b;
}
}
EDIT: If you want utility to do it you can wrap it in some functional interface and then call it.
static boolean isNullResult(Callable call) throws Exception {
try {
return call.call() == null;
} catch (NullPointerException npe) {
return true;
}
}
Usage will be the following:
isNullResult(new Callable<Integer>() {
#Override
public Integer call() throws Exception {
return new A().getB().getC().getInt();
}
});
It won't require you to change existing functionality
As already stated, the true solution is refactoring.
In the meantime, you could just wrap your first workaround in a function:
static D getD(MyClass obj) {
try {
return obj.getA().getB().getC().getD();
}
catch (NullPointerException e) {
return null; // Or even better, some default D
}
}
At the caller site:
D d = getD(obj);
At least you don't have to trash the caller with try-catch blocks. You still need to handle the errors somehow, when some of the intermediate getX() call returns a null and so d becomes null. The best would be to return some default D in the wrapper function.
I don't see how the two options you list at the end of your question would help if any of the intermediate getX() returns a null; you will get a NullPointerException.

Is there a simpler way to derefence nullable references in Java?

Consider the following Code Snippet:
if (foo != null
&& foo.bar != null
&& foo.bar.boo != null
&& foo.bar.boo.far != null)
{
doSomething (foo.bar.boo.far);
}
My question is simple: is there a more simple\shorter way to do this ?
In detail: is there a more simple way to validate each part of the chain, I'd imagine similar to this ..
if (validate("foo.bar.boo.far"))
{
doSomething (foo.bar.boo.far);
}
Maybe like that ?
if (FooUtils.isFarNotEmpty(foo)){
doSomething (foo.bar.boo.far);
}
and in FooUtils :
boolean isFarNotEmpty (Foo foo){
return foo != null &&
foo.bar != null &&
foo.bar.boo != null &&
foo.bar.boo.far != null;
}
In my opinion this expression is perfect, nothing can be simpler
why you are using public instance variable, encapsulate your public variables and create getter and setter for them and you can perform these check in your getter, and you can return new Object() if any of them is null, or you can run this statement in try-catch block but not recommended,
If this is your API please consider some advice.
"I call it my billion-dollar mistake." - Sir C. A. R. Hoare, on his
invention of the null reference
There's not much you can do with this, unfortunately. If you ask me, it's a problem with the Java language. Groovy has something called the Safe Navigation Operator ?. that is specifically for this purpose. Here are two things I've done in the past.
The answer that Grisha already gave, so I won't repeat it
Naively wrote code that accesses it, and surround it in a try/catch for a NPE. Here's an example:
try {
if (foo.bar.boo.far != null) {
//do something
}
} catch (NullPointerException e) {
//do what you would do in an else
}
I don't particularly like the 2nd option, but I say if it actually makes the code cleaner, consider using it.
One time I was working with a library that is a very thin wrapper over an XML schema and I decided to use the 2nd option for this case. If I didn't, the code would have been harder to maintain because it would be so easy to forget a null check and they cluttered up the important logic. I think that's a valid case for using it.
Please try this code
try {
if (foo.bar.boo.far != null) {
//No object is null
}
} catch (Exception e) {
// some object is null and causes null point exception.
}

Categories

Resources