在每个 if-else 情况下执行语句的最佳方式

gru*_*uvw 5 c if-statement

我经常发现自己在 if-else 链的所有分支的末尾重复一些代码:

例子:

if (cond1) {
    // [...] code 1

    // repeated code
} else if (cond2) {
    // [...] code 2

    // repeated code
} else if (cond3) {
    // [...] code 3

    // repeated code
}
Run Code Online (Sandbox Code Playgroud)

遵循DRY 原则的最佳方法是什么?

我想到了以下几点:

  • 将重复的代码放在一个函数中:您仍然需要在每个分支中重复调用该函数。
  • 在 if-else 链之后有一个新的 if 条件(所有先前条件的大“或”):您需要重复先前的条件。
  • 为什么不存在这样的东西?finally我希望可以在 if-else 链之后使用一个类似于异常的关键字。仅当前面的条件之一为真时,它才会执行代码:
if (cond1) {
    // [...] code 1
} else if (cond2) {
    // [...] code 2
} else if (cond3) {
    // [...] code 3
} wrapup {
    // repeated code
}
Run Code Online (Sandbox Code Playgroud)

您如何在代码中解决这个问题?

注意:这个问题被标记为该C语言,但我也有兴趣看到其他编程语言的解决方案,这些语言可能对这种程序流/路径有一个很好的构造。

chu*_*ica 6

设置一个标志

if (cond1) {
    // [...] code 1
    // repeated code
} else if (cond2) {
    // [...] code 2
    // repeated code
} else if (cond3) {
    // [...] code 3
    // repeated code
}
Run Code Online (Sandbox Code Playgroud)

-->

repeat = true;
if (cond1) {
    // [...] code 1
} else if (cond2) {
    // [...] code 2
} else if (cond3) {
    // [...] code 3
} else {
  repeat = false;
}

if (repeat) {
  // repeated code
}
Run Code Online (Sandbox Code Playgroud)


Eri*_*hil 6

//  Start block in which we expect to do wrap-up code except in unmatched case.
do
{
    if (Condition0)
    {
        Code0;
    }
    else if (Condition1)
    {
        Code1;
    }
    else if (Condition2)
    {
        Code2;
    }
    else
        break;

    //  Perform the wrap-up code in all cases except the above else-break.
    WrapUpCode;
} while (0);
Run Code Online (Sandbox Code Playgroud)