rspec/rules/S2789/java/rule.adoc

42 lines
994 B
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
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.
2021-04-28 16:49:39 +02:00
== 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
}
----
2021-04-28 16:49:39 +02:00
== 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();
}
----