42 lines
994 B
Plaintext
42 lines
994 B
Plaintext
The concept of ``++Optional++`` is that it will be used when ``++null++`` could cause errors. In a way, it replaces ``++null++``, and when ``++Optional++`` is in use, there should never be a question of returning or receiving ``++null++`` from a call.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
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
|
|
|
|
----
|
|
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();
|
|
}
|
|
----
|
|
|