重构 if 和 else if 之间的公共代码

本文关键字:if 代码 之间 else 重构 | 更新日期: 2023-09-27 18:33:44

我有一个如果...else if 语句如下:

  If(x > y && order.invoice != 1)
    {
       DoSomething();
       x = x + y;
    }
     else if(order.invoice == 1)
     {
       x = x + y;
     } 

有没有更好的方法来重构它。我感觉不好 x = x + y 在 if 和 else if 中。

重构 if 和 else if 之间的公共代码

if (order.invoice != 1 && x > y) {
    DoSomething();
}
if (order.invoice == 1 || x > y) {       
   x = x + y;
}    

您可以执行两次赋值,也可以执行两次 if 语句之一。 这个计算很简单,我不会担心它。

不过,它可以这样缩短:

if(x > y && order.invoice != 1)
    {
       DoSomething();
       x += y;
    }
     else if(order.invoice == 1)
     {
       x += y;
     } 

另一种选择可能是使用标志来查看是否增加,但复杂性和单个调用与简单性和半冗余代码之间仍然存在相同的拉锯战。

bool increment = false;
if(x > y && order.invoice != 1)
    {
       DoSomething();
       increment = true;
    }
     else if(order.invoice == 1)
     {
       increment = true
     } 
if (increment) { x += y; }

这是重构它的证明/系统方法。入手:

if (x > y && order.invoice != 1)
{
    DoSomething();
    x = x + y;
}
else if (order.invoice == 1)
{
    x = x + y;
} 

所以问题是,哪组输入导致x = x + y?井:

x = x + y
<=> (x > y && order.invoice != 1) ||
    (!(x > y && order.invoice != 1) && order.invoice == 1)
<=> (x > y && order.invoice != 1) ||
    ((x <= y || order.invoice == 1) && order.invoice == 1)
<=> (x > y && order.invoice != 1) ||
    ((x <= y && order.invoice == 1) || (order.invoice == 1 && order.invoice == 1)
<=> (x > y && order.invoice != 1) ||
    ((x <= y && order.invoice == 1) || order.invoice == 1)
<=> (x > y && order.invoice != 1) ||
    order.invoice == 1
<=> (x > y || order.invoice == 1) && (order.invoice != 1 || order.invoice == 1)
<=> (x > y || order.invoice == 1)

因此它相当于

if (x > y && order.invoice != 1)
{
    DoSomething();
}
if (x > y || order.invoice == 1)
{
    x = x + y;
}

您还可以使用真值表

x > y | order.invoice == 1  |   x = x + y
F     | F                   |   N
F     | T                   |   Y
T     | F                   |   Y
T     | T                   |   Y

这又给了你

x = x + y
<=> !(x <= y && order.invoice != 1)
<=> x > y || order.invoice == 1

最后,我不同意这种重构,除非它实际上使代码更容易理解。保存代码行并不意味着您使代码更具可读性(因此不会使其更具可读性)显然更易于维护)