2023-05-03 11:06:20 +02:00
== Why is this an issue?
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
2023-05-03 11:06:20 +02:00
=== Noncompliant code example
2020-06-30 12:48:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:48:39 +02:00
----
Optional<String> value = this.getOptionalValue();
// ...
String stringValue = value.get(); // Noncompliant
----
2022-02-04 17:28:24 +01:00
[source,java]
2021-09-02 18:11:19 +02:00
----
if (methodThatReturnsOptional().isEmpty()) {
throw new NotFoundException();
}
String value = methodThatReturnsOptional().get(); // Noncompliant: indirect access, we consider that two consecutive calls can return different values.
----
2023-05-03 11:06:20 +02:00
=== Compliant solution
2020-06-30 12:48:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-09-02 18:11:19 +02:00
----
this.getOptionalValue().ifPresent(stringValue ->
// Do something with stringValue
);
----
or
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:48:39 +02:00
----
Optional<String> value = this.getOptionalValue();
// ...
if (value.isPresent()) {
String stringValue = value.get();
}
----
or
2022-02-04 17:28:24 +01:00
[source,java]
2020-06-30 12:48:39 +02:00
----
Optional<String> value = this.getOptionalValue();
// ...
String stringValue = value.orElse("default");
----
2022-02-04 17:28:24 +01:00
[source,java]
2021-09-02 18:11:19 +02:00
----
Optional<String> optional = methodThatReturnsOptional();
2021-09-03 13:36:27 +02:00
if (optional.isEmpty()) {
2021-09-02 18:11:19 +02:00
throw new NotFoundException();
}
String value = optional.get();
----
2020-06-30 12:48:39 +02:00
include::../see.adoc[]
2021-06-02 20:44:38 +02:00
2021-06-03 09:05:38 +02:00
ifdef::env-github,rspecator-view[]
2021-09-20 15:38:42 +02:00
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
call "xxx.isPresent()" before accessing the value.
2021-09-20 15:38:42 +02:00
2021-06-08 15:52:13 +02:00
'''
2021-06-02 20:44:38 +02:00
== Comments And Links
(visible only on this page)
include::../comments-and-links.adoc[]
2021-06-03 09:05:38 +02:00
endif::env-github,rspecator-view[]