满屏的if-else,怎么消灭它们?

开发 前端
过多的if-else不仅导致程序运行效率低下,而且导致代码圈复杂度过高。如果大家有使用过静态代码分析工具,就会知道圈复杂度是衡量代码质量的一项重要的指标,圈复杂度越高,代码出现bug的可能性也越大。

[[386493]]

本文转载自微信公众号「程序喵大人」,作者程序喵大人。转载本文请联系程序喵大人公众号。

之前我曾经在知乎写过一篇回答,详细介绍了if-else的效率问题。

 

过多的if-else不仅导致程序运行效率低下,而且导致代码圈复杂度过高。如果大家有使用过静态代码分析工具,就会知道圈复杂度是衡量代码质量的一项重要的指标,圈复杂度越高,代码出现bug的可能性也越大。

我们可能刚开始写的代码很简洁,只有一个if-else分支,但由于需求的叠加和各种错误处理,我们有时候不得已要多加几个if-else,久而久之就发现,满屏的if-else,令你极其讨厌自己写的代码。

至于如何消灭if-else,可谓八仙过海各显神通,这里介绍几种常见的方法:

巧用表结构:一般如果某些条件可存储,可以考虑把条件存起来用于去掉if-else,例如:

  1. long long func() { 
  2.     const unsigned ARRAY_SIZE = 50000; 
  3.     int data[ARRAY_SIZE]; 
  4.     const unsigned DATA_STRIDE = 256; 
  5.  
  6.     for (unsigned c = 0; c < ARRAY_SIZE; ++c) data[c] = std::rand() % DATA_STRIDE; 
  7.     long long sum = 0; 
  8.  
  9.     for (unsigned c = 0; c < ARRAY_SIZE; ++c) { 
  10.         if (data[c] >= 128) sum += data[c]; 
  11.     } 
  12.     return sum

可以通过表结构去掉代码中的if分支

  1. long long func() { 
  2.     const unsigned ARRAY_SIZE = 50000; 
  3.     int data[ARRAY_SIZE]; 
  4.     const unsigned DATA_STRIDE = 256; 
  5.     int lookup[DATA_STRIDE]; 
  6.     for (unsigned c = 0; c < DATA_STRIDE; ++c) { 
  7.         lookup[c] = (c >= 128) ? c : 0; 
  8.     } 
  9.  
  10.     for (unsigned c = 0; c < ARRAY_SIZE; ++c) data[c] = std::rand() % DATA_STRIDE; 
  11.     long long sum = 0; 
  12.  
  13.     for (unsigned c = 0; c < ARRAY_SIZE; ++c) { 
  14.         sum += lookup[data[c]]; 
  15.     } 
  16.     return sum

使用switch-case替换if-else:一般情况下switch-case比if-else效率高一些,而且逻辑也更清晰,例如:

  1. void func() { 
  2.     if (a == 1) { 
  3.         ... 
  4.     } else if (a == 2) { 
  5.         ... 
  6.     } else if (a == 3) { 
  7.         ... 
  8.     } else if (a == 4) { 
  9.         ... 
  10.     } else { 
  11.         ... 
  12.     } 

try-catch替换:if-else很多情况下都用于错误处理,如果我们使用try-catch处理错误,是不是就可以消灭if-else了呢,拿数值运算代码举例:

  1. class Number { 
  2. public
  3.   friend Number operator+ (const Number& x, const Number& y); 
  4.   friend Number operator- (const Number& x, const Number& y); 
  5.   friend Number operator* (const Number& x, const Number& y); 
  6.   friend Number operator/ (const Number& x, const Number& y); 
  7.   // ... 
  8. }; 

最简单的可以这样调用:

  1. void f(Number x, Number y) { 
  2.   // ... 
  3.   Number sum  = x + y; 
  4.   Number diff = x - y; 
  5.   Number prod = x * y; 
  6.   Number quot = x / y; 
  7.   // ... 

但是如果需要处理错误,例如除0或者数值溢出等,函数得到的就是错误的结果,调用者需要做处理。

先看使用错误码的方式:

  1. class Number { 
  2. public
  3.   enum ReturnCode { 
  4.     Success, 
  5.     Overflow, 
  6.     Underflow, 
  7.     DivideByZero 
  8.   }; 
  9.   Number add(const Number& y, ReturnCode& rc) const; 
  10.   Number sub(const Number& y, ReturnCode& rc) const; 
  11.   Number mul(const Number& y, ReturnCode& rc) const; 
  12.   Number div(const Number& y, ReturnCode& rc) const; 
  13.   // ... 
  14. }; 
  15.  
  16. int f(Number x, Number y) 
  17.   // ... 
  18.   Number::ReturnCode rc; 
  19.   Number sum = x.add(y, rc); 
  20.   if (rc == Number::Overflow) { 
  21.     // ...code that handles overflow... 
  22.     return -1; 
  23.   } else if (rc == Number::Underflow) { 
  24.     // ...code that handles underflow... 
  25.     return -1; 
  26.   } else if (rc == Number::DivideByZero) { 
  27.     // ...code that handles divide-by-zero... 
  28.     return -1; 
  29.   } 
  30.   Number diff = x.sub(y, rc); 
  31.   if (rc == Number::Overflow) { 
  32.     // ...code that handles overflow... 
  33.     return -1; 
  34.   } else if (rc == Number::Underflow) { 
  35.     // ...code that handles underflow... 
  36.     return -1; 
  37.   } else if (rc == Number::DivideByZero) { 
  38.     // ...code that handles divide-by-zero... 
  39.     return -1; 
  40.   } 
  41.   Number prod = x.mul(y, rc); 
  42.   if (rc == Number::Overflow) { 
  43.     // ...code that handles overflow... 
  44.     return -1; 
  45.   } else if (rc == Number::Underflow) { 
  46.     // ...code that handles underflow... 
  47.     return -1; 
  48.   } else if (rc == Number::DivideByZero) { 
  49.     // ...code that handles divide-by-zero... 
  50.     return -1; 
  51.   } 
  52.   Number quot = x.div(y, rc); 
  53.   if (rc == Number::Overflow) { 
  54.     // ...code that handles overflow... 
  55.     return -1; 
  56.   } else if (rc == Number::Underflow) { 
  57.     // ...code that handles underflow... 
  58.     return -1; 
  59.   } else if (rc == Number::DivideByZero) { 
  60.     // ...code that handles divide-by-zero... 
  61.     return -1; 
  62.   } 
  63.   // ... 

再看使用异常处理的方式:

  1. void f(Number x, Number y) 
  2.   try { 
  3.     // ... 
  4.     Number sum  = x + y; 
  5.     Number diff = x - y; 
  6.     Number prod = x * y; 
  7.     Number quot = x / y; 
  8.     // ... 
  9.   } 
  10.   catch (Number::Overflow& exception) { 
  11.     // ...code that handles overflow... 
  12.   } 
  13.   catch (Number::Underflow& exception) { 
  14.     // ...code that handles underflow... 
  15.   } 
  16.   catch (Number::DivideByZero& exception) { 
  17.     // ...code that handles divide-by-zero... 
  18.   } 

如果有更多的运算,或者有更多的错误码,异常处理的优势会更明显。

提前return:对于某些错误处理可以考虑提前return,直接看代码:

  1. void func(A *a) { 
  2.     if (a) { 
  3.         ... 
  4.     } else { 
  5.         log_error(...); 
  6.         return
  7.     } 

适当情况下通过反转if条件就可以删除掉else分支。

合并分支表达式:有些情况下可以通过合并表达式来消除if-else,例如:

  1. void func() { 
  2.     if (a < 20) return
  3.     if (b > 30) return
  4.     if (c < 18) return

可以改为

  1. void func() { 
  2.     if (a < 20 || b > 30 || c < 18) return

策略模式:熟悉设计模式的同学可能都知道,一般代码中if-else过多,那就可以考虑使用策略模式啦,例如:

  1. enum class CalOperation { 
  2.     add
  3.     sub 
  4. }; 
  5.  
  6. int NoStragegy(CalOperation ope) { 
  7.     if (ope == CalOperation::add) { 
  8.         std::cout << "this is add operation" << std::endl; 
  9.     } else if (ope == CalOperation::sub) { 
  10.         std::cout << "this is sub operation" << std::endl; 
  11.     } // 如何将来需要增加乘法或者除法或者其它运算,还需要增加if-else 
  12.     return 0; 

这种if-else可以通过策略模式进行消除:

  1. #ifndef __CALCULATION__ 
  2. #define __CALCULATION__ 
  3.  
  4. #include <iostream> 
  5.  
  6. class Calculation { 
  7.    public
  8.     Calculation() {} 
  9.  
  10.     virtual ~Calculation() {} 
  11.  
  12.     virtual void operation() { std::cout << "base operation" << std::endl; } 
  13. }; 
  14.  
  15. #endif 
  16.  
  17. #ifndef __ADD__ 
  18. #define __ADD__ 
  19.  
  20. #include "calculation.h" 
  21.  
  22. class Add : public Calculation { 
  23.     void operation() override { std::cout << "this is add operation" << std::endl; } 
  24. }; 
  25.  
  26. #endif 
  27. #ifndef __SUB__ 
  28. #define __SUB__ 
  29.  
  30. #include "calculation.h" 
  31.  
  32. class Sub : public Calculation { 
  33.     void operation() override { std::cout << "this is sub operation" << std::endl; } 
  34. }; 
  35.  
  36. #endif 
  37. int Stragegy() { 
  38.     Calculation *cal = new Add(); 
  39.     cal->operation(); 
  40.     delete cal; 
  41.  
  42.     Calculation *cal2 = new Sub(); // 这里将来都可以用工厂模式改掉,不会违反开放封闭原则 
  43.     cal2->operation(); 
  44.     delete cal2; 
  45.  
  46.     return 0; 

将来如果有乘法除法和其它运算规则,只需要再加一个继承基类的子类即可。方便扩展,且遵循设计原则。

职责链模式:职责链模式尽管不能消灭if-else,但它可以用于改良if-else,使其更灵活,例如:

  1. #include <iostream> 
  2.  
  3. using std::cout; 
  4.  
  5. void func(int num) { 
  6.     if (num >= 0 && num <= 10) { 
  7.         cout << "0-10 \n"
  8.     } else if (num > 10 && num <= 20) { 
  9.         cout << "10-20 \n"
  10.     } else if (num > 20 && num <= 30) { 
  11.         cout << "20-30 \n"
  12.     } else if (num > 30 && num <= 40) { 
  13.         cout << "30-40 \n"
  14.     } else if (num > 40 && num <= 50) { 
  15.         cout << "40-50 \n"
  16.     } else if (num > 50 && num <= 60) { 
  17.         cout << "50-60 \n"
  18.     } else { 
  19.         cout << "not handle \n"
  20.     } 
  21.  
  22. int main() { 
  23.     func(25); 
  24.     func(43); 
  25.     return 0; 

可以考虑改为下面的形式:

  1. #include <iostream> 
  2.  
  3. using std::cout; 
  4.  
  5. struct Handle { 
  6.     virtual void process(int num) {} 
  7. }; 
  8.  
  9. struct Handle1 : public Handle { 
  10.     Handle1(Handle *processor) : processor_(processor) {} 
  11.  
  12.     void process(int num) override { 
  13.         if (num >= 0 && num <= 10) { 
  14.             cout << "0-10 \n"
  15.         } else { 
  16.             processor_->process(num); 
  17.         } 
  18.     } 
  19.  
  20.     Handle *processor_; 
  21. }; 
  22.  
  23. struct Handle2 : public Handle { 
  24.     Handle2(Handle *processor) : processor_(processor) {} 
  25.  
  26.     void process(int num) override { 
  27.         if (num >= 10 && num <= 20) { 
  28.             cout << "10-20 \n"
  29.         } else { 
  30.             processor_->process(num); 
  31.         } 
  32.     } 
  33.  
  34.     Handle *processor_; 
  35. }; 
  36.  
  37. struct Handle3 : public Handle { 
  38.     Handle3(Handle *processor) : processor_(processor) {} 
  39.  
  40.     void process(int num) override { 
  41.         if (num >= 20 && num <= 30) { 
  42.             cout << "20-30 \n"
  43.         } else { 
  44.             cout << "not handle \n"
  45.         } 
  46.     } 
  47.  
  48.     Handle *processor_; 
  49. }; 
  50.  
  51. int main() { 
  52.     Handle *handle3 = new Handle3(nullptr); 
  53.     Handle *handle2 = new Handle2(handle3); 
  54.     Handle *handle1 = new Handle2(handle2); 
  55.     handle1->process(24); 
  56.     handle1->process(54); 
  57.     return 0; 
  58. 三目运算符:某些简单情况下可以使用三目运算符消灭if-else,例如: 
  59. int func(int num) { 
  60.     if (num > 20) return 1; 
  61.     else return 0; 

三目运算符:某些简单情况下可以使用三目运算符消灭if-else,例如:

  1. int func(int num) { 
  2.     if (num > 20) return 1; 
  3.     else return 0; 

可以改为:

  1. int func(int num) { 
  2.     return num > 20 ? 1 : 0; 

这样是不是代码也更清晰了一些。

else-if消除:有时候有些人写的代码确实就是这样,例如:

  1. int func(int num) { 
  2.     int ret = 0; 
  3.     if (num == 1) { 
  4.         ret = 3; 
  5.     } else if (num == 2) { 
  6.         ret = 5; 
  7.     } else { 
  8.         ret = 6; 
  9.     } 
  10.     return ret; 
  11. }  

是不是可以考虑改为:

  1. int func(int num) { 
  2.     if (num == 1) return 3; 
  3.     if (num == 2) return 5; 
  4.     return 6; 

 

责任编辑:武晓燕 来源: 程序喵大人
相关推荐

2021-04-13 06:39:13

代码重构code

2020-04-20 15:40:03

if-elseJava优化

2020-03-11 08:00:12

if-else优化运算符

2023-06-02 07:30:24

If-else结构流程控制

2013-03-06 10:28:57

ifJava

2021-11-04 08:53:00

if-else代码Java

2022-07-11 08:16:55

策略模式if-else

2020-10-22 09:20:22

SQLNoSQL 数据库

2020-04-09 08:29:50

编程语言事件驱动

2021-05-17 14:57:23

策略模式代码

2020-12-15 09:31:58

CTOif-else代码

2020-05-13 14:15:25

if-else代码前端

2021-01-29 07:45:27

if-else代码数据

2020-09-27 14:24:58

if-else cod业务

2023-11-14 08:00:00

Angular前端开发

2024-04-26 08:58:54

if-else代码JavaSpring

2022-07-04 08:32:55

Map函数式接口

2022-04-12 07:32:40

引擎模式Spring策略模式

2024-03-25 10:00:00

C++编程else

2022-11-04 11:18:16

代码优化可读性
点赞
收藏

51CTO技术栈公众号