Search code examples
javaif-statementpmd

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 fact about all three versions). Is this a false positive or is there a better way of writing the if-condition?


Solution

  • 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.