How to avoid object != null condition check in Java?

0 votes
730 views
asked Jan 18, 2019 by Hitesh Garg (355 points)  

We were having a lot of NullPointerExceptions in our system due to which we end up having a lot of object != null conditions in our code.

Although some places we are sure that the Null pointer will never be thrown from a certain section of code but when someone else is implementing the code then we are not sure whether it will throw Null pointer or not and then we end up having the same condition again, which is completely useless.

Is there any other alternative for that?

For example:

if (someobject != null) {
    someobject.doCalc();
}

1 Answer

0 votes
answered Feb 5 by Hitesh Garg (355 points)  
 
Best answer

Java 8 Optional

Java 8 comes with a new class Optional that solves some of the null checking problem.
It makes the intent of the code clear that the value can or can not be present and the person calling the value should consider that.

Example

public static Optional<String> find(@NotNull String name) {
      if (name.equals("Codingeek")) {
         return Optional.of("Success");
      }
   return Optional.empty();
}

// Prints "Success"
find("Codingeek")
    .ifPresentOrElse(System.out::println, () -> System.out.println("It is empty"));

// Prints "It is empty"
find("something")
    .ifPresentOrElse(System.out::println, () -> System.out.println("It is empty"));

Using @Nullable and @NotNull

If you are planning to use some IDE with good Java suppport then these annotations can be used as IDEs identify these annotations and dont allow you to do unnecessary checks or miss important checks.

@NotNull public static String hello() { return "Hello World"; }

// Intellij will complain about this and will inform
// you about the unnecessary check
  if(hello() != null) {
       ...
  }

or

// Wont compile in Intellij
@Nullable public static String hello() {return "Hello World";}

The same things happen when you use @NotNull annotation with the parameters and inside the method, you can be sure that this value is never null. Example

void someMethod(@NotNull someParameter) { }
...