开发者

Java collapsible if statements

I use PMD to check my code. It gives me very useful hints in most cases, but I can't figure out what could be improved in the following scenario.

The original code looks something like this:

if ((getSomething() != null && getSomethingElse() != null)
     || (getSomething() == null && getSomethingElse() == null))
{
   ...
}

PMD tells me:

Sometimes two 'if' statements can be consolidated by separating their conditions with a boolean short-circuit operator.

For simplicity, let's just use a and b as boolean variables. Then this piece of code looks like this:

if ((!a && !b) || (a && b))

This can be transformed to one of the following:

if ((!a || b) && (a || !b))
if (!(a^b))

and finally

if (a==b)

So I simplified my code to

if ((getSomething() == null) == (getSomethingElse() == null))

However, PMD keeps complaining (in f开发者_高级运维act about all three versions). Is this a false positive or is there a better way of writing the if-condition?


The problem was something different. The if-statement was the only code inside another if (the code comes from a validation-method):

if (...)
{
   ...
}
else if (...)
{
   ...
}
else if (...)
{
   if ((getSomething() == null) == (getSomethingElse() == null))
   {
      ...
   }
}

What the PMD-message means, is that I could combine the conditions of the last else-if and the inner if-clause:

if (...)
{
   ...
}
else if (...)
{
   ...
}
else if (... && ((getSomething() == null) == (getSomethingElse() == null)))
{
      ...
}

However, I'm not sure, if I'll do this, because the original version seems much clearer to understand.


if ((a != null) && (b != null) && (a==b))

..although personally, I'd do the null checking prior to this if statement so I could handle the a == null and b == null cases individually


The issue is that large blocks of conditionals are difficult to reason about.

OTOH, not every warning PMD emits needs to be paid attention to--consider the ROI. Is it worth refactoring or restructuring to make it cleaner? Can the same functionality be handled in a different way?

If it's not worth it, don't bother.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜