rspec/rules/S3655/java/rule.adoc

72 lines
1.7 KiB
Plaintext
Raw Normal View History

2021-01-27 13:42:22 +01:00
``++Optional++`` value can hold either a value or not. The value held in the ``++Optional++`` can be accessed using the ``++get()++`` method, but it will throw a
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
``++NoSuchElementException++`` if there is no value present. To avoid the exception, calling the ``++isPresent()++`` or ``++! isEmpty()++`` method should always be done before any call to ``++get()++``.
2020-06-30 12:48:39 +02:00
2021-02-02 15:02:10 +01:00
2021-01-27 13:42:22 +01:00
Alternatively, note that other methods such as ``++orElse(...)++``, ``++orElseGet(...)++`` or ``++orElseThrow(...)++`` can be used to specify what to do with an empty ``++Optional++``.
2020-06-30 12:48:39 +02:00
== Noncompliant Code Example
----
Optional<String> value = this.getOptionalValue();
// ...
String stringValue = value.get(); // Noncompliant
----
----
if (methodThatReturnsOptional().isEmpty()) {
throw new NotFoundException();
}
String value = methodThatReturnsOptional().get(); // Noncompliant: indirect access, we consider that two consecutive calls can return different values.
----
2020-06-30 12:48:39 +02:00
== Compliant Solution
----
this.getOptionalValue().ifPresent(stringValue ->
// Do something with stringValue
);
----
or
2020-06-30 12:48:39 +02:00
----
Optional<String> value = this.getOptionalValue();
// ...
if (value.isPresent()) {
String stringValue = value.get();
}
----
or
----
Optional<String> value = this.getOptionalValue();
// ...
String stringValue = value.orElse("default");
----
----
Optional<String> optional = methodThatReturnsOptional();
if (methodThatReturnsOptional().isEmpty()) {
throw new NotFoundException();
}
String value = optional.get();
----
2020-06-30 12:48:39 +02:00
include::../see.adoc[]
ifdef::env-github,rspecator-view[]
'''
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
endif::env-github,rspecator-view[]