[英]Synchronized statements - are synchronized method and synchronized statements equivalent?
[英]Are these statements equivalent?
我可以像这样重构,这些是等价的,因此更简单直接的代码版本是首选吗?
在重构之前:
if (!matcher.matches() && !matcher2.matches() && !matcher3.matches()
&& !matcher4.matches() && !matcher5.matches()
&& !matcher6.matches() && !matcher7.matches()
&& !matcher8.matches()) {
return true;
} else
return false;
重构后:
return (matcher.matches() || matcher2.matches() || matcher3.matches()
|| matcher4.matches() || matcher5.matches()
|| matcher6.matches() || matcher7.matches()
|| matcher8.matches())
实际上,没有。 只有当所有匹配器不匹配时,第一个才是true
。 如果所有匹配器在第二个语句中不匹配,则返回false
return !(matcher.matches() || matcher2.matches() || matcher3.matches()
|| matcher4.matches() || matcher5.matches()
|| matcher6.matches() || matcher7.matches()
|| matcher8.matches())
这是对的
不,他们不等同。 你必须添加!
在第二个选项面前。
固定的第二个选项更加清晰:
return !(matcher.matches() || matcher2.matches() || matcher3.matches()
|| matcher4.matches() || matcher5.matches()
|| matcher6.matches() || matcher7.matches()
|| matcher8.matches())
我也会这样重构:
boolean atLeastOneMatch = matcher.matches() || matcher2.matches() || matcher3.matches()
|| matcher4.matches() || matcher5.matches()
|| matcher6.matches() || matcher7.matches()
|| matcher8.matches();
return !atLeastOneMatch;
不,这些不等同。 稍微削减它以便更清楚 - 让我们只使用2个示例,并将它们设为x和y而不是“matcherX.matches()”。 在这种情况下,你要问:
这两个是等价的吗?
if (!x && !y) {
return true;
} else
return false;
和
return (x || y);
让我们轻松进入它。 首先,初始陈述可以直接转换为
return (!x && !y);
这是真相表 :
| x | y | !x && !y |
+---------+---------+------------+
| T | T | F |
| T | F | F |
| F | T | F |
| F | F | T |
也就是说,第一个表达式返回true
只有当没有子表达式为true。 那是一样的
return !(x || y);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.