【问题标题】:Are these statements equivalent?这些陈述是否等效?
【发布时间】:2012-09-14 06:32:24
【问题描述】:

我可以像这样重构吗,这些是否等效,因此更简单的代码版本是首选?

重构前:

    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()) 

【问题讨论】:

  • 是的,差不多:en.wikipedia.org/wiki/De_Morgan%27s_laws(你可能需要在最后应用一个额外的反转。不过我还没有检查。)
  • 实际上,任何有价值的 IDE 都会为您执行此重构。 Eclipse 使用 Ctrl + 1 和 IntelliJ 使用 Alt + Enter

标签: java refactoring boolean-logic demorgans-law


【解决方案1】:

实际上,没有。第一个是true,仅当所有匹配器匹配时。如果第二个语句中的所有匹配器都不匹配,则返回false

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

这是正确的

【讨论】:

    【解决方案2】:

    不,它们不相等。您必须在第二个选项前面添加!

    固定的第二个选项肯定更清楚:

    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;
    

    【讨论】:

      【解决方案3】:

      不,这些不相等。将其缩减一点,以便更清楚 - 让我们仅使用 2 个示例,并将它们设为 x 和 y 而不是“matcherX.matches()”。在这种情况下,您是在问:

      这两个是等价的吗?

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

      return (x || y);
      

      让我们轻松进入它。首先,初始语句可以清楚地直接转换为

      return (!x && !y);
      

      这是Truth Table

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

      也就是说,只有当没有子表达式为真时,第一个表达式才返回true。和这个一样

      return !(x || y);
      

      【讨论】:

        猜你喜欢
        • 2011-01-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-02-01
        • 2017-06-11
        • 2023-04-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多