如何避免“如果”連鎖? - How to avoid “if” chains?

問題:

Assuming I have this pseudo-code: 假設我有這個僞代碼:

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

executeThisFunctionInAnyCase();

Functions executeStepX should be executed if and only if the previous succeed. 僅當前一個成功時才應執行函數executeStepX In any case, the executeThisFunctionInAnyCase function should be called at the end. 無論如何,應該在最後調用executeThisFunctionInAnyCase函數。 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? 我在編程的新手,對於非常基本的問題,很抱歉:有沒有辦法(在C / C ++爲例),以避免長if鏈生產之類的“代碼金字塔”,在代碼的代價易讀?

I know that if we could skip the executeThisFunctionInAnyCase function call, the code could be simplified as: 我知道,如果我們可以跳過executeThisFunctionInAnyCase函數調用,則代碼可以簡化爲:

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

But the constraint is the executeThisFunctionInAnyCase function call. 但是約束是executeThisFunctionInAnyCase函數調用。 Could the break statement be used in some way? 可以以某種方式使用break語句嗎?


解決方案:

參考一: https://en.stackoom.com/question/1eVUO
參考二: https://stackoom.com/question/1eVUO
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章