rspec/rules/S5411/java/rule.adoc

56 lines
1.2 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
When boxed type ``++java.lang.Boolean++`` is used as an expression it will throw ``++NullPointerException++`` if the value is ``++null++`` as defined in https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.8[Java Language Specification §5.1.8 Unboxing Conversion].
It is safer to avoid such conversion altogether and handle the ``++null++`` value explicitly.
Note, however, that no issues will be raised for Booleans that have already been null-checked.
2021-04-28 16:49:39 +02:00
== Noncompliant Code Example
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
Boolean b = getBoolean();
if (b) { // Noncompliant, it will throw NPE when b == null
foo();
} else {
bar();
}
----
2021-04-28 16:49:39 +02:00
== Compliant Solution
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
Boolean b = getBoolean();
if (Boolean.TRUE.equals(b)) {
foo();
} else {
bar(); // will be invoked for both b == false and b == null
}
----
[source,java]
----
Boolean b = getBoolean();
if(b != null){
String test = b ? "test" : "";
}
----
2021-04-28 16:49:39 +02:00
== See
* https://docs.oracle.com/javase/specs/jls/se8/html/jls-5.html#jls-5.1.8[Java Language Specification §5.1.8 Unboxing Conversion]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
include::message.adoc[]
include::highlighting.adoc[]
endif::env-github,rspecator-view[]