1

In my code, I am making a lot of checks for null so that I don't get a NullPointerException usually i am just doing like this:

if(variable != null){
    //do something with the variable
}

Is the following better in any way or is it just a matter or personal belief?

if( !variable.equals(null) ){
    //do something with the variable
}

Is there a more efficient way to make this check?

Btw I do have done my research already but I cant seem to find concrete evidence to prove either point.

P.S This is a NOT duplicate of Avoiding != null statements, on that the best answer is that you should either use Assert, which cannot be used to run code rather than just display a message, or actually throw the exception which I dont want either. This post is addressing a different issue of the same subject.

Community
  • 1
  • 1
Sir. Hedgehog
  • 1,260
  • 3
  • 17
  • 40
  • 3
    Possible duplicate of [Avoiding != null statements](http://stackoverflow.com/questions/271526/avoiding-null-statements) – Pradeep Simha Aug 18 '16 at 13:30
  • 2
    How would the second be better? It will throw a NullPointerException when `variable` is null – OneCricketeer Aug 18 '16 at 13:30
  • @cricket_007 that is true, but my aim was, to show that i meant to use `.equals` – Sir. Hedgehog Aug 18 '16 at 13:33
  • @you could use [Object#equals](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html) like `Objects.equals(null, variable)`. But in fact that would be the same as `variable == null` just written different. – SomeJavaGuy Aug 18 '16 at 13:34
  • 2
    I think the actual solution here might depend on how you want to handle the value when you do find null (or not). Like using an `Optional`, for example – OneCricketeer Aug 18 '16 at 13:37
  • 1
    I always prefer correctness over personal belief. Especially other people's personal belief. – Kayaman Aug 18 '16 at 13:45

5 Answers5

4
 if(!variable.equals(null) ){
     //do something with the variable
 }

If variable is null NPE occurs. First method is far better.

EDIT: Using Optional: Consider that you have Person object and want to getSalary(). Unfortunately age can be null - in that case you want default value. You can do Integer salary = Optional.ofNullable(person.getSalary()).orElse(2000). It will return salarty from person or 2000 in case salary is null.

ByeBye
  • 6,650
  • 5
  • 30
  • 63
  • Thanks for the answer, but Is there maybe a better way than the first one then to do it? – Sir. Hedgehog Aug 18 '16 at 13:31
  • 1
    Agree - you should use this if(variable != null){} – P_M Aug 18 '16 at 13:31
  • 1
    There is not better way to checking if something is null or not. Based on you need you can consider using of `Optional` from Java8 or just trying to not passing `null` values in you code. – ByeBye Aug 18 '16 at 13:32
  • @ByeBye i am trying not to, but you never know ^^ could you provide an example with the `Optional` that you mentioned? – Sir. Hedgehog Aug 18 '16 at 13:35
  • 1
    consider that you have `Person` object and want to `getSalary()`. unfortunately `age` can be null - in that case you want default value. You can do `Integer salary = Optional.ofNullable(person.getSalary()).orElse(2000)`. It will return salarty from person or 2000 in case salary is null. – ByeBye Aug 18 '16 at 13:40
  • thats a very good answer, please add that in your answer post. – Sir. Hedgehog Aug 18 '16 at 13:41
2

As others already said, the variant

if(!variable.equals(null))

can NPE itself when variable is null. Furthermore, you have to be sure that the equals method also is null-safe for all object types you use. Thus, if you absolutely need to check, use ==.

As for better solutions (we're going opinion-based here): I think that this ecessive null-checking is a sign of brittle software and suboptimal interface definition. What I currently try to do more and more is use the javax.validation annotation @NotNull to harden my interfaces and get rid off all these runtime checks:

private @NotNull String getName() {...} // guaranteed not to return null
...
if(getName() == null) { // superfluos, your IDE gives a shout if configurd correctly
   ...
}

... give it a shot :)

Edit (as an answer to the comment, as I need code-formatting):

Here's a complete cut&paste-example from my current eclipse setup:

package stuff;

import javax.validation.constraints.NotNull;

public class Try3 {
   public @NotNull String getName() { return ""; }

   public void test() {
      if(getName() == null)
         System.out.println("Cannot happen due to contract");
   }
}

Ensure, that the imported type is indeed javax.validation.constraints.NotNull (as other frameworks also have a NotNull annotation, which may be defined in a different way). For eclipse, you also have to check "Enable annotation-based null analysis" in the project settings under JavaCompiler / Errors/Warnings and customize the annotations to use, as eclipse defaults to some home-brewed annotations. The customization can be accessed via the link "Configure" after the checkbox for using default annotations in the same settings page. Hope that helps!

mtj
  • 3,381
  • 19
  • 30
  • I did try what you recommended but when trying to add the `@NotNull` to the method, i am getting a `The annotation @NotNull is disallowed for that location`..... And i have it the same way as yours, `private @NotNull String getStr() { return ""; }` – Sir. Hedgehog Aug 18 '16 at 14:28
  • for some reason, i keep getting errors, also the IDE keeps on asking to change the import with the `@com.esotericsoftware.kryo.NotNull` – Sir. Hedgehog Aug 19 '16 at 07:29
  • If it is a maven project, add the dependency javax.validation.validation-api (1.1.0.Final) - otherwise, check where you get that library. – mtj Aug 19 '16 at 07:52
2

Or you can use java.util.Optional from Java 8.

Very nice examples are on JavaCodeGeeks.

Optional is usually used in java.util.stream lambdas for "functional-style operations".

1

There are two approaches:

public void calculate(Class variable) {
    Assert.notNull(variable, "variable was null");
    //calculations
}
//and
if (variable == null) {
    //bad
} else {
    calculate(variable);
}

The second one is the most common one. If your variable is a String consider using Guava.StringUtils with it's fantastic isBlank method which checks if the String is null or ""

Summarizing:

if (variable == null) {
    //bad
} else {
    //good
}

The above is standard approach. The better approach will be:

private boolean isNull(Class variable) {
    return variable == null;
}

if (isNull(variable)) {

} else {

}
xenteros
  • 15,586
  • 12
  • 56
  • 91
0

I used to do call the below method all the time which checks for nullpointer exception

public static boolean isAvailable(Object data) {
        return ((data!=null) && (data.toString().trim().length() > 0));
    } 
Karthik
  • 545
  • 6
  • 23
  • hmmm possible answer, but i think its not efficient as if you need other situation controls you wont be able to configure.... thanks though – Sir. Hedgehog Aug 18 '16 at 13:43