Java tuning tutorial 3 - Tuning NPE.RET to reduce false positives
Java tuning tutorial 3 - Tuning NPE.RET to reduce false positivesLet's say we have a snippet: package com.klocwork.jdefects.checkers.dfa.binding_walkthrough; public class CheckSample1 { public String toString() { final Object o = get(); return o.toString(); } private Object get() { if (hashCode() > 0 ) { return new Object(); } return null; } } An analysis with kwcheck detects the NPE.RET issue, where null comes from the get()and is dereferenced at o.toString(). Add an assertion to fix the errorTo fix the NPE.RET issue, add assertNotNull(o); to the code: package com.klocwork.jdefects.checkers.dfa.binding_walkthrough; public class CheckSample1 { public String toString() { final Object o = get(); assertNotNull(o); return o.toString(); } private Object get() { if (hashCode() > 0 ) { return new Object(); } return null; } } Create a .jkb file and describe the method as the checkAfter we add the assertion and re-run the analysis, NPE.RET is still reported because the call to assertNotNull is the call to the library method, about which Klocwork does not have any specific information.
package junit.framework; class Assert { public static void assertNotNull(@Check Object object); } Note: This step is also captured for Eclipse and IntelliJ IDEA users.
Bind the Check record to the checkerAfter you add @Check, bind the data to the issue, using @Bind("NPE.RET"): package junit.framework; @Bind("NPE.RET") class Assert { public static void assertNotNull(@Check Object object); }
Test the knowledge baseTo test your knowledge base:
When the code is analyzed using this knowledge base, Klocwork now knows assertNotNull is the check; consequently, NPE.RET is not reported. |