rspec/rules/S5411/java/rule.adoc

31 lines
847 B
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.
== Noncompliant Code Example
----
Boolean b = getBoolean();
if (b) { // Noncompliant, it will throw NPE when b == null
foo();
} else {
bar();
}
----
== Compliant Solution
----
Boolean b = getBoolean();
if (Boolean.TRUE.equals(b)) {
foo();
} else {
bar(); // will be invoked for both b == false and b == null
}
----
== 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]