Optional
acts as a container object that may or may not contain a non-null value. It is introduced in Java 8 to help avoid
NullPointerException
. It provides methods to check if a value is present and retrieve the value if it is present.
Optional
is used instead of null
values to make the code more readable and avoid potential errors.
It is a bad practice to use null
with Optional
because it is unclear whether a value is present or not, leading to
confusion and potential NullPointerException
errors.
There are a few ways to fix this issue:
null
from a method whose return type is Optional
. Optional
and use Optional
methods instead, like isPresent()
or
ifPresent()
. public void doSomething () { Optional<String> optional = getOptional(); if (optional != null) { // Noncompliant // do something with optional... } Optional<String> text = null; // Noncompliant, a variable whose type is Optional should never itself be null // ... } @Nullable // Noncompliant public Optional<String> getOptional() { // ... return null; // Noncompliant }
public void doSomething () { Optional<String> optional = getOptional(); optional.ifPresent( // do something with optional... ); Optional<String> text = Optional.empty(); // ... } public Optional<String> getOptional() { // ... return Optional.empty(); }