如何避免“如果"链?

How to avoid quot;ifquot; chains?(如何避免“如果链?)

本文介绍了如何避免“如果"链?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这个伪代码:

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

executeThisFunctionInAnyCase();

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

Functions executeStepX should be executed if and only if the previous succeed. In any case, the executeThisFunctionInAnyCase function should be called at the end. I'm a newbie in programming, so sorry for the very basic question: is there a way (in C/C++ for example) to avoid that long if chain producing that sort of "pyramid of code", at the expense of the code legibility?

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

I know that if we could skip the executeThisFunctionInAnyCase function call, the code could be simplified as:

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

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

But the constraint is the executeThisFunctionInAnyCase function call. Could the break statement be used in some way?

推荐答案

您可以使用 &&(逻辑与):

You can use an && (logic AND):

if (executeStepA() && executeStepB() && executeStepC()){
    ...
}
executeThisFunctionInAnyCase();

这将满足您的两个要求:

this will satisfy both of your requirements:

  • executeStep() 仅在前一个成功时才应评估(这称为 短路评估)
  • executeThisFunctionInAnyCase() 任何情况下都会执行
  • executeStep<X>() should evaluate only if the previous one succeeded (this is called short circuit evaluation)
  • executeThisFunctionInAnyCase() will be executed in any case

这篇关于如何避免“如果"链?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:如何避免“如果"链?

基础教程推荐