Modify rule S2789: Update rule according to the LayC (#2395)

This commit is contained in:
Angelo 2023-07-05 11:27:09 +02:00 committed by GitHub
parent 721147819e
commit 4a6ac45dd7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 27 additions and 15 deletions

View File

@ -9,14 +9,6 @@
"tags": [
"java8"
],
"extra": {
"replacementRules": [
],
"legacyKeys": [
]
},
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-2789",
"sqKey": "S2789",

View File

@ -1,11 +1,24 @@
== 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.
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.
`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.
=== Noncompliant code example
== How to fix it
[source,java]
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();
@ -23,10 +36,8 @@ public Optional<String> getOptional() {
}
----
=== Compliant solution
[source,java]
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
public void doSomething () {
Optional<String> optional = getOptional();
@ -43,6 +54,15 @@ public Optional<String> getOptional() {
}
----
== 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[]
'''