java - 冗余 If 消息

标签 java netbeans

我的 Fraction 程序运行流畅,但 NetBeans IDE 告诉我以下 if 是多余的:

public boolean equals(Object other)
{
  Fraction bool = (Fraction) other;

  if(this.numerator == bool.numerator && this.denominator == bool.denominator)
  {
   return true;
  }
  else return false;       
} 

上面的代码完美地编译/运行并通过了所有测试用例,但是 NetBeans 的冗余标志真的让我很困扰。我将 reduceToLowestTerms() 添加到我的代码中,标志消失了,但我的构造函数中已经有了 reduceToLowestTerms()。这是非冗余代码(根据 NetBeans )的样子:

public boolean equals(Object other)
{
        Fraction bool = (Fraction) other;

        if(this.numerator == bool.numerator && this.denominator == bool.denominator)
        {
         bool.reduceToLowestTerms();
         this.reduceToLowestTerms();
         return true;
        }
         else return false;       
    } 

如有任何建议,我们将不胜感激

最佳答案

这看起来类似于我的 IDE 对此语句发出的警告:

'if' statement can be simplified

if(foo())
{
   return true;
}
else
{
   return false;
}

can be simplified to

return foo();

这只是过于复杂和冗长的代码。您的简化是:

return this.numerator == bool.numerator && this.denominator == bool.denominator;

但是正如您所注意到的,您的代码已经是正确的。这个改动不是必须的,但是会让代码更简洁,更简单。

添加对另一个方法 (reduceToLowestTerms()) 的调用会移除此“标志”的原因是代码无法再以这种方式简化为单个返回声明。

关于java - 冗余 If 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28821081/

相关文章:

java - 如何从另一台计算机连接到sql server

java - JsonPath:按数组中任意数组中的值进行过滤

java - 为什么drawImage没有在jframe上绘制图像

java - 每个问题的 JSTL

用于监控笔记本电脑电池或电源的Java代码

java - 尝试运行使用绝对布局的 JAR 时出现 NoClassDefFoundError

c++ - 如何在 NetBeans 中使用 Microsoft C++ 编译器?

java - 每个派生表都必须有自己的别名。如何在sql代码中添加别名

java - 我可以使用正文以外的编码发送 POST 表单吗?

java - 如何添加一个没有 xml 配置的 RequestContextListener?