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) { }