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.
}
Related
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.
Working with hibernate I use this sort of code many times:
int someId = entity.getSomething() == null ? null : entity.getSomething().getId();
This code becomes a little more messy when trying to apply on a longer hierarchy:
int someId = entity.getParent() == null ? null :
entity.getParent().getParent() == null ? null :
entity.getParent().getParent().getSomething() == null ? null :
entity.getParent().getParent().getSomething().getId();
Is there a more elegant way to do it?
As per Louis Wasserman's comment, Optional can almost be used as a NullObject a'la flogy's solution.
Using Java 8 Optional and lambdas it looks like this
Integer value = Optional.ofNullable(entity)
.map( Entity::getParent )
.map( Entity::getParent )
.map( Entity::getSomething )
.map( Something::getId )
.orElse(null);
In case those entity objects are written by yourself and not in a library, I would consider refactoring them and use NullObjects. Like that you could then directly call
Integer someId = entity.getParent().getParent().getSomething().getId();
as this would then return your nulled integer.
Basically, it works like this:
entity.getParent() will return a NullParent instance
this NullParent class has a method getParent(), which also will return a NullParent instance
again, this NullParent class has a method getSomething(), which will return a NullSomething instance
the NullSomething class has a method getId(), which finally will return your nulled integer (e.g. 0 or another NullInteger object).
Here is an interesting post on Why NULL is bad?
Is there a more elegant way to do it?
You may simply go for try-catch for null check:
try{
int id = entity.getParent().getParent().getSomething().getId();
// do something with id
} catch(NullPointerException ex) {
// got null
}
You're assigning the same null value if it's null.
Why don't you try giving it only if it is not null.
if(x != null) x = y
Readability is very important factor as well as the simplification of code. It is better to use simple if condition here.
if(entity.getParent()!=null && entity.getParent().getParent() !=null &&
entity.getParent().getParent().getSomething()!=null &&
entity.getParent().getParent().getSomething().getId()!=null){
}
And because of &&("short-circuit and"), if one condition false non other condition in the right execute.
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.
I have this line code:
String name = Book.getName();
/*next lines of code*/
Next, variable name processing in other code without any checks.
In some cases, possible situation, when name=null and other code will exit with an error.
It is bad.
Also, I cant access to the other code.
So, what do you think, my next implementation is correct:
try
{
String name = Book.getName();
if(null== name)
throw new NullPointerException("method 'getName' return null");
/*next lines of code*/
}
catch(NullPointerException e)
{
System.out.print("Hey! Where book name? I exit!");
System.exit();
}
I have any other choose in this case?
It is possible to generate any other type of Exception or only NullPointerException?
Thanks.
Edit:
Ok,
String name = Book.getName();
it's imagine code line. In real case, I have more complex code:
List<Book> bookList= new ArrayList<Book>();
String name = null;
Iterator i = BookShop.getBooks.iterator(); //BookShop it is input parameter!
while(i.hasNext())
{
Book book = (Book) i.next;
name = book.getName();
nameList.add(name);
}
This example more full.
So, in this code input parameter BookShop Object.
What problem I can have with this Object?
BookShop can be NULL;
method BookShop.getBooks() can return NULL;
Also, getName() can return NULL too.
So, general problem next: there is no guarantee the correctness of input parameter BookShop!
And I must to consider every possible option (3 NULL)
For me, add General try-catch block and that all.
No?
You can create any exception you like by extending the Exception class, like a NoNameProvidedException for example. There are a lot of example one Google to help you do that.
I guess in your case just checking with an if if the name is null should be sufficient as you just want to do a System.exit().
Your code is a bit iffy, but I assume you're learning. You don't need to throw the NullPointerException explicitly, you can throw whatever Exceptions you like.
But you probably don't really need the Exception catching here, you can just check for the null and handle the situation appropriately if it's true.
Also, please avoid Yoda conditions. Your if statement should read
if name is null
so
if (name == null)
I would probably use IllegalStateException:
String name = Book.getName();
if (name == null) {
throw new IllegalStateException
("Method foo must not be called when the book has no name");
}
It really depends on where the state is coming from though - it's not really clear what's going wrong here.
I certainly wouldn't start catching NullPointerException - exceptions like that (and the illegal state one) shouldn't be explicitly caught. Let them bubble up, and if it's appropriate have some sort of top-level handler.
Exceptions should not be used for normal control flow. Just use the if block:
String name = Book.getName();
if (name == null) {
System.out.print("Hey! Where book name? I exit!");
System.exit();
}
/*next lines of code*/
Using try and catch in this case is unneeded. You can just write like this:
if(Book.getName() != null)
String name = Book.getName();
else
//handle the situation with null
You don't need to throw an Exception in this case - just handle the null value and you are fine.
It's more friendly for Java not to use exceptions, but just check the return value
String name = Book.getName();
if (name == null)
System.out.print("Hey! Where book name? I exit!");
else {
/*next lines of code*/
}
In java, Which of the following is the more "accepted" way of dealing with possibly null references? note that a null reference does not always indicate an error...
if (reference == null) {
//create new reference or whatever
}
else {
//do stuff here
}
or
try {
//do stuff here
}
catch (NullPointerException e) {
//create new reference or whatever
}
The answers already given are excellent (don't use exceptions for control flow; exceptions are expensive to throw and handle). There's one other important reason specifically not to catch NullPointerException.
Consider a code block that does the following:
try {
reference.someMethod();
// Some other code
}
catch (NullPointerException e) {
// 'reference' was null, right? Not so fast...
}
This might seem like a safe way to handle nullity of reference ...but what if reference was non-null and someMethod() raised NPE? Or what if there was a NPE raised elsewhere in the try block? Catching NPE is a surefire way to prevent bugs from being found and fixed.
Catching exceptions is relatively expensive. It's usually better to detect the condition rather than react to it.
Of course this one
if (reference == null) {
//create new reference or whatever
}
else {
//do stuff here
}
we shouldn't rely on exception for decision making, that aren't given for that purpose at all, also they are expensive.
Well If you aren't making decision and just verifying for initialized variable then
if (reference == null) {
//create new reference or whatever
}
//use this variable now safely
I have seen some auto code generator wraps up this thing in accessors/getter method.
I think in general an exception should be reserved for exceptional circumstances - if a null reference is sometimes expected, you should check for it and handle it explicitly.
From the answers its clear that catching an exception is not good. :)
Exceptions are definitely not free of cost. This might help you to understand it in depth. .
I would also like to mention an another practice while comparing your object with a known value.
This is the traditional way to do the job: (check whether the object is null or not and then compare)
Object obj = ??? //We dont know whether its null or not.
if(obj!=null && obj.equals(Constants.SOME_CONSTANT)){
//your logic
}
but in this way, you dont have to bother about your object:
Object obj = ???
if(Constants.SOME_CONSTANT.equals(obj)){ //this will never throw
//nullpointer as constant can not be null.
}
The first one, throwing exceptions is a costly operation.
The first form:
if (reference == null)
{
//create new reference or whatever
}
else
{
//do stuff here
}
You should not use exceptions for control flow.
Exceptions are for handling exceptional circumstances that would not normally occur during normal operating conditions.
You should use exception catching where you do not expect there to be an error. If something can be null, then you should check for that.
maybe the try catch approach will start making sense in this situation when we can start doing
try {
//do stuff here
}
catch (NullPointerException e) {
//create new reference or whatever
retry;
}
This is related to your style of development, if you are developing code using "safe" style you have to use
if(null == myInstance){
// some code
}else{
// some code
}
but if you do not use this style at least you should catch exception, but in this case it NullPointerException and I think preferably to check input parameters to null and not wait to throwing exception.
Since you asked for Best Practices, I want to point out that Martin Fowler suggests to introduce a subclass for null references as best practice.
public class NullCustomer extends Customer {}
Thus, you avoiding the hassle of dealing with NullPointerException's, which are unchecked. Methods which might return a Customer value of null, would then instead return a NullCustomer instead of null.
Your check would look like:
final Customer c = findCustomerById( id );
if ( c instanceof NullCustomer ) {
// customer not found, do something ...
} else {
// normal customer treatment
printCustomer( c );
}
In my opinion, it is permissible in some cases to catch a NullPointerException to avoid complex checks for null references and enhance code readability, e.g.
private void printCustomer( final Customer c ) {
try {
System.out.println( "Customer " + c.getSurname() + " " + c.getName() + "living in " + c.getAddress().getCity() + ", " + c.getAddress().getStreet() );
} catch ( NullPointerException ex ) {
System.err.println( "Unable to print out customer information.", ex );
}
An argument against it is that by checking for individual members being null, you can write a more detailed error message, but that is often not necessary.