Skip to content

Files

Latest commit

 

History

History
51 lines (34 loc) · 1.22 KB

UnnecessaryNullCheck.md

File metadata and controls

51 lines (34 loc) · 1.22 KB

Pattern: Unnecessary null check

Issue: -

Description

Groovy contains the safe dereference operator. It can be used in boolean conditional statements to safely replace explicit x == null tests. Also, testing the this or super reference for null equality is pointless and can be removed.

Examples of violations:

if (obj != null && obj.method()) { }

if (obj != null && obj.prop) { }

// this is pointless and won't avoid NullPointerException
if (obj.method() && obj != null ) { }

if (this == null) { }
if (null == this) { }
if (this != null) { }
if (null != this) { }

if (super == null) { }
if (null == super) { }
if (super != null) { }
if (null != super) { }

Examples of acceptable code:

// null check it OK
if (obj != null) { }

// null safe dereference in if is OK
if (obj?.method()) { }

// null safe dereference in ternary is OK
(obj?.prop && obj?.prop2) ? x : y

// obj is reused in a parameter list, so OK
if (obj != null && obj.method() && isValid(obj)) { }

// rule is not so complex yet...
(obj != null && obj.prop && obj.method()) ? x : y

Further Reading