How to fix the following PMD violations

sarahTheButterFly picture sarahTheButterFly · Jan 5, 2011 · Viewed 17k times · Source

I am using PMD to analyze code and it produces a few high priority warnings which I do not know how to fix.

1) Avoid if(x!=y)..; else...; But what should I do if I need this logic? That is, I do need to check if x!=y? How can I refactor it?

2) Use explicit scoping instead of the default package private level. But the class is indeed used only within the package. What access modifier should I use?

3) Parameter is not assigned and could be declared final. Should I add final keyword to all the places which PMD pointed out with this warning?

Answer

mhaller picture mhaller · Jan 5, 2011

Avoid negation: Instead of if( x!=y ) doThis() else doThat(), check for the positive case first, because people/humans tend to like positive things more than negative. It twists the brain to have to reverse the logic in mind when reading the source code. So instead, write:

 if ( x!=y ) doThis() else doThat()       // Bad - negation first
 if ( x==y ) doThat() else doThis()       // Good - positive first

Explicit scoping: According to PMD website, it's a controversial rule. You may hate it, someone else likes it. What you should do is make all the fields within your classes private. There seems to be a field or method (not a class) with a package visibility, e.g. something like this:

 class Foo {
   /* private missing */ Object bar;
 }

Final parameters: Method parameters should be final to avoid accidental reassignment. That's just a good practice. If you're using Eclipse, the content assist even provides a quickfix called "Change modifiers to final where possible". Just select all code in the editor with Ctrl-a and then press Ctrl-1.