冗余如果消息

lro*_*408 1 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;       
} 
Run Code Online (Sandbox Code Playgroud)

上面的代码编译/运行完美并传递了所有测试用例,但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;       
    } 
Run Code Online (Sandbox Code Playgroud)

任何建议将不胜感激

rge*_*man 8

这看起来类似于我的IDE在此声明中给出的警告:

'if'语句可以简化

if(foo())
{
   return true;
}
else
{
   return false;
}
Run Code Online (Sandbox Code Playgroud)

可以简化为

return foo();
Run Code Online (Sandbox Code Playgroud)

它只是过于复杂和冗长的代码.您的简化将是:

return this.numerator == bool.numerator && this.denominator == bool.denominator;
Run Code Online (Sandbox Code Playgroud)

但是正如您所注意到的,您的代码已经是正确的.没有必要进行此更改,但它将使代码更简洁,更简化.

添加对另一个方法(reduceToLowestTerms())的调用删除此"标志"的原因是代码不再以这种方式简化为单个return语句.