Suranga Suranga - 1 month ago 14
Java Question

if(x!=y) vs if(x==y)

I have run the PMD plugin in Eclipse against my code and I'm getting a high priority warning for code similar to the one shown below:

if(singleRequest !=null){
// do my work
}else{
// do my other work
}


PMD says
`Avoid if (x != y) ..; else ..
;

And the description of the error looks like this:

In an "if" expression with an "else" clause, avoid negation in
the test. For example, rephrase:
if (x != y) diff(); else same();
as:
if (x == y) same(); else diff();
Most "if (x != y)" cases without an "else" are often return


but I still can't understand the impact on my code. If someone could guide me with an example, I would appreciate it.

Answer Source

A number of PMD rules are more style opinions than correctness alerts. If you don't agree with this rule or the rule doesn't match your project's coding standards, you could consider suppressing warnings or even configuring PMD to enforce only the rules you like