My First Post      My Facebook Profile      My MeOnShow Profile      W3LC Facebook Page      Learners Consortium Group      Job Portal      Shopping @Yeyhi.com









Thursday, May 28, 2020

Assigning an Object to null is a code smell. Consider refactoring.

Suppose You get following NullAssignment violation PMD error:



<pmd xmlns="http://pmd.sourceforge.net/report/2.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://pmd.sourceforge.net/report/2.0.0 http://pmd.sourceforge.net/report_2_0_0.xsd" version="6.8.0" timestamp="2020-05-29T15:00:32.203"> <file name="/Users/mfaiz/<path>/www/seva/platform/integration/test/framework/controller/StartController.java"> <violation beginline="61" endline="61" begincolumn="21" endcolumn="24" rule="NullAssignment" ruleset="Error Prone" package="<path>integration.test.framework.controller" class="StartController" method="start" externalInfoUrl="https://pmd.github.io/pmd-6.8.0/pmd_rules_java_errorprone.html#nullassignment" priority="3"> Assigning an Object to null is a code smell. Consider refactoring. </violation>



Issue:
Setting a variable to null just removes a reference to the object. it does not change the actual object.If you need to clean up, you most likely need to do actions to the object referenced by your variable instead.


Another easy solution:

Just set your variable to final.

For instance, if there is the following code, SONAR will report as a code smell:

private Object obj = null;
However, if you just add final, it can be resolved.

private final Object obj = null;

No comments:

Post a Comment