重构空的if语句

时间:2019-01-07 06:29:00

标签: java if-statement refactoring readability

我目前正在研究一个项目,该项目需要删除其他不同类正在使用的类。在某些情况下,我可以删除由该类组成的一行代码,在此情况下它永远不会影响程序的功能,但是在某些情况下,您要删除的类位于if语句内。主要问题是,一旦我删除了包含该类的代码行,如果它在if语句内的位置,它将是一个空的if语句,它将违反声纳。

除了否定其中一个语句的条件之外,还有另一种重构空if语句的方法吗?因为当我只求条件时,代码的可读性降低了。

例如:

if((example_A >= 0) && (condition_A))
{
     removeThisClass();
}
else if((example_B >= )) && (condition_B))
{
     doSomething();
}
else
{
     doAnything();
}

重构:

if(!((example_A >= 0) && (condition_A)) && ((example_B >= )) && (condition_B)))
{
     doSomething();
}
else
{
     doAnything();
}

3 个答案:

答案 0 :(得分:1)

您可以将此代码放在单独的方法(https://refactoring.com/catalog/extractFunction.html)中,并这样编写:

public void DoSomeStuff() {

  if((example_A >= 0) && (condition_A))
    return;  

  if((example_B >= )) && (condition_B)) {
    doSomething();
    return;
  }

  doAnything();
}    

答案 1 :(得分:0)

如果我理解的正确,应该删除removeThisClass();行,并且您不希望留下这样的空块:

if((example_A >= 0) && (condition_A))
{
}
else if((example_B >= )) && (condition_B))
{
    doSomething();
}
else
{
    doAnything();
}

为了不进行两次“ A”测试,您需要取消该条件,例如像这样:

if ((example_A < 0) || ! (condition_A))
{
    if ((example_B >= )) && (condition_B))
    {
        doSomething();
    }
    else
    {
        doAnything();
    }
}

您的重构代码是错误的,因为如果条件为“ A”,则原始代码将执行removeThisClass();,这意味着它现在不应该执行任何操作,但是当“ A”是正确的。

答案 2 :(得分:0)

您可以发表评论。声纳should accept that,它也可以帮助读者。

void doSomething() {
  for (int i = 0; i < 42; i++)        // Non-Compliant
  {
  }
  for (int i = 0; i < 42; i++);       // Compliant

  if (myVar == 4)                     // Compliant - contains a comment
  {
    // Do nothing because of X and Y
  }
  else                                // Compliant
  {
    doSomething();
  }

  try                                 // Non-Compliant
  {
  }
  catch (Exception e)                 // Compliant
  {
    // Ignore
  }
}