Question

Can I refactor like this, are these equivalent and therefore the simpler straighforward version of the code is preferred?

Before refactoring:

    if (!matcher.matches() && !matcher2.matches() && !matcher3.matches()
            && !matcher4.matches() && !matcher5.matches()
            && !matcher6.matches() && !matcher7.matches()
            && !matcher8.matches()) {
        return true;
    } else
        return false;

After refactoring:

    return (matcher.matches() || matcher2.matches() || matcher3.matches()
            || matcher4.matches() || matcher5.matches()
            || matcher6.matches() || matcher7.matches()
            || matcher8.matches()) 
Was it helpful?

Solution

No, they are not equivalent. You have to add ! in front of the second option.

The fixed second option is more clear for sure:

return !(matcher.matches() || matcher2.matches() || matcher3.matches()
            || matcher4.matches() || matcher5.matches()
            || matcher6.matches() || matcher7.matches()
            || matcher8.matches()) 

I will also refactor it this way:

boolean atLeastOneMatch = matcher.matches() || matcher2.matches() || matcher3.matches()
                || matcher4.matches() || matcher5.matches()
                || matcher6.matches() || matcher7.matches()
                || matcher8.matches();

return !atLeastOneMatch;

OTHER TIPS

Actually, no. The first one is true only when all matchers don't match. If all matchers don't match in the second statement, you return false

return !(matcher.matches() || matcher2.matches() || matcher3.matches()
            || matcher4.matches() || matcher5.matches()
            || matcher6.matches() || matcher7.matches()
            || matcher8.matches()) 

This is correct

No, these are not equivalent. Pare it down a bit so it's clearer - let's use just 2 examples, and make them x and y instead of "matcherX.matches()". You're asking, in that case:

Are these two equivalent?

if (!x && !y) {
        return true;
    } else
        return false;

and

return (x || y);

Let's ease our way into it. First, the initial statement can clearly be transformed directly to

return (!x && !y);

Here's the Truth Table for that:

|    x    |    y    |  !x && !y  |
+---------+---------+------------+
|    T    |    T    |     F      |
|    T    |    F    |     F      |
|    F    |    T    |     F      |
|    F    |    F    |     T      |

That is, the first expression returns true only when none of the subexpressions is true. That's the same as

return !(x || y);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top