如何避免“if”链?

新手上路,请多包涵

假设我有这个伪代码:

 bool conditionA = executeStepA();
if (conditionA){
    bool conditionB = executeStepB();
    if (conditionB){
        bool conditionC = executeStepC();
        if (conditionC){
            ...
        }
    }
}

executeThisFunctionInAnyCase();

函数 executeStepX 当且仅当前一个成功时才应该执行。无论如何,应该在最后调用 executeThisFunctionInAnyCase 函数。我是编程新手,很抱歉这个非常基本的问题:有没有办法(例如在 C/C++ 中)避免产生那种“代码金字塔”的长 if 链,以牺牲代码的易读性为代价?

我知道如果我们可以跳过 executeThisFunctionInAnyCase 函数调用,代码可以简化为:

 bool conditionA = executeStepA();
if (!conditionA) return;
bool conditionB = executeStepB();
if (!conditionB) return;
bool conditionC = executeStepC();
if (!conditionC) return;

但约束是 executeThisFunctionInAnyCase 函数调用。可以以某种方式使用 break 语句吗?

原文由 ABCplus 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 654
1 个回答

我认为 C++23 的可选单子操作会做得很好,尽管必须对函数进行一些更改。

and_then() 方法执行 break 或 call next 函数操作,并且链接该方法允许一个一个地调用函数,直到其中一个返回 false。

举一个快速而肮脏的例子:

 #include <iostream>
#include <optional>
#include <cstdlib>

using namespace std;

optional<bool> func1() {
    cout << "func1\n";

    if (rand() % 2)
        return true;
    else
        return nullopt;
}

optional<bool> func2(optional<bool> v) {
    cout << "func2\n";

    if (rand() % 2)
        return true;
    else
        return nullopt;
}

optional<bool> func3(optional<bool> v) {
    cout << "func3\n";

    if (rand() % 2)
        return true;
    else
        return nullopt;
}

void func4() {
    cout << "func4\n";
}

int main() {
    srand(time(NULL));

    func1()
      .and_then(func2)
      .and_then(func3);

    func4();

    return 0;
}

原文由 Uri Raz 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题