diff --git a/rules/S2789/java/metadata.json b/rules/S2789/java/metadata.json index 89941eaeb4..8b0dcfc407 100644 --- a/rules/S2789/java/metadata.json +++ b/rules/S2789/java/metadata.json @@ -9,14 +9,6 @@ "tags": [ "java8" ], - "extra": { - "replacementRules": [ - - ], - "legacyKeys": [ - - ] - }, "defaultSeverity": "Major", "ruleSpecification": "RSPEC-2789", "sqKey": "S2789", diff --git a/rules/S2789/java/rule.adoc b/rules/S2789/java/rule.adoc index 4a701b2e01..bed31f14ef 100644 --- a/rules/S2789/java/rule.adoc +++ b/rules/S2789/java/rule.adoc @@ -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 optional = getOptional(); @@ -23,10 +36,8 @@ public Optional getOptional() { } ---- - -=== Compliant solution - -[source,java] +==== Compliant solution +[source,java,diff-id=1,diff-type=compliant] ---- public void doSomething () { Optional optional = getOptional(); @@ -43,6 +54,15 @@ public Optional 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[] '''