81 lines
2.2 KiB
Plaintext
81 lines
2.2 KiB
Plaintext
== Why is this an issue?
|
|
`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.
|
|
|
|
== How to fix it
|
|
|
|
There are a few ways to fix this issue:
|
|
|
|
* Avoid returning `null` from a method whose return type is `Optional`.
|
|
* Remove the null-check of an `Optional` and use `Optional` methods instead, like `isPresent()` or `ifPresent()`.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
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
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
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();
|
|
}
|
|
----
|
|
|
|
== Resources
|
|
|
|
=== Documentation
|
|
|
|
* https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/util/Optional.html[Oracle SDK 20 - Optional]
|
|
|
|
=== Articles & blog posts
|
|
* https://www.baeldung.com/java-optional[Java Optional Guide]
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
* Remove this null-check of an "Optional".
|
|
* Methods with an "Optional" return type should never return null.
|
|
* Methods with an "Optional" return type should not be "@Nullable".
|
|
* "Optional" variables should not be "@Nullable".
|
|
|
|
|
|
endif::env-github,rspecator-view[]
|