技术宅,fat-man

增加语言的了解程度可以避免写出愚蠢的代码

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

转载:如何避免代码中的if嵌套

http://top.jobbole.com/4960/

http://stackoverflow.com/questions/24430504/how-to-avoid-if-chains

 

在Stack Overflow上的一个挺有趣的问题,详细整理问题和部分巧妙的回答如下。

假设我刻意写了一段代码:

复制代码
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是必须的,我该如何重构if条件嵌套呢?

 


 

 

感觉最好的方案:

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

猪头点评:

粗粗看来这是最好的方案,因为他简洁明白,极大的减少了代码,不过个人认为表达式不宜太复杂,如果子表达式超过3个,或者executeStep需要提供复杂的函数参数,那么就合适再写一个函数,把executeStepA() && executeStepB() && executeStepC()包装起来。

 

其他方案:

do {
    if (!executeStepA()) break;
    if (!executeStepB()) break;
    if (!executeStepC()) break;
  doSomething(); }
while(0); executeThisFunctionInAnyCase();

猪头点评:

这个方案也是不错的,如果不希望对代码做大的调整,这个方案可以增加一个层次,用来控制是否执行doSomething(),同时代码也被极大的简化了

 

复制代码
void Execute()
{
   if (!executeStepA()) return;
   if (!executeStepB()) return;
   if (!executeStepC()) return;

   doSometing();
}
 
Execute();
ExecuteThisFunctionInAnyCase();
复制代码

猪头点评:

这个方案实际上是猪头一开始也想到的方案,一样达到效果,不过对比之前的方案,显然还是复杂了,因为他搞出一个函数来,虽然第一个方案也可能需要包装一个函数,但明显还是比这个方案简单,因为那个方案是复杂度到了才需要加函数,这个方案是一开始就要搞出一个函数,而不看内部复杂度

 

goto版本:

 

复制代码
void execute()
{
    if(!executeStepA()) goto error;
    if(!executeStepB()) goto error;
    if(!executeStepC()) goto error;
    
    doSomething();

error:
    executeThisFunctionInAnyCase();
}
复制代码

 

猪头点评:

这个方案看起来也不错,看起来goto用的好也能发挥不错的作用

 

 

 

posted on   codestyle  阅读(1180)  评论(0编辑  收藏  举报

编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
历史上的今天:
2013-07-09 Mongodb
2013-07-09 360的开源项目
2012-07-09 运行python-thrift的DEMO
2012-07-09 Apache Thrift 安装配置
点击右上角即可分享
微信分享提示