Are these statements equivalent?

Can I reorganize it like this, are they equivalent, and therefore a simpler 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()) 
+4
source share
3 answers

No, they are not equivalent. You must add ! before the second option.

The fixed second option is more clear:

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

I will also reorganize it like this:

 boolean atLeastOneMatch = matcher.matches() || matcher2.matches() || matcher3.matches() || matcher4.matches() || matcher5.matches() || matcher6.matches() || matcher7.matches() || matcher8.matches(); return !atLeastOneMatch; 
+2
source

No, actually. The first is true only if all matches do not match . If all matches do not match in the second expression, you return false

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

It is right.

+6
source

No, they are not equivalent. Eliminate this a bit, so it’s clearer - let's just use 2 examples and make them x and y instead of “matcherX.matches ()”. In this case, you ask:

Are these two equivalents?

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

and

 return (x || y); 

Free your way. First, the original operator can be explicitly converted directly to

 return (!x && !y); 

Here's the truth table for this:

 | 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. Same as

 return !(x || y); 
0
source

Source: https://habr.com/ru/post/1434132/


All Articles