如何避免过多嵌入if-else

How to avoid too much embedded if-else?

本文关键字:if-else 何避免      更新时间:2023-10-16

如下:

if(...){
    if(...){
    }else{
       ...
    }
}else if(...){
    if(...){
    }else{
       ...
    }
}else{
    ...
}

在编码中总是遇到这种情况,它看起来太可怕了。如何避免?

没有一般规则。但是,两种常见的情况是:

  1. 当切换/案例可以帮助您减少代码量时
  2. 当您应该使用状态机来设计代码时

根据您的需要和代码,这些可能是更好的解决方案。

假设:您希望根据if-else梯形图中检查的结果调用某些函数。

如果你有一个附带的索引,它是用你在if-else条件中检查的值计算的,那么如果梯形图太大,那么拥有函数指针的静态数组可能会对你大有裨益。

例如。

uint8_t x;
uint8_t y;
if(x == 1)
{
  if (y == 1)
       call11();
  else if (y==2)
       call12();
}
else if( x == 2)
{
  if (y == 1)
       call21();
  else if (y==2)
       call22();
.
.
.
}
else if(x ==3)
.
.
.

上面的代码可以替换为下面的

typedef void (*FuncPtr)();
FunPtr array[65535];
//intialize at once with some function
void initFunArray()
{
 array[1*256 + 1] = call11;
 array[1*256 + 2] = call12;
....
 array[2*256 + 1] = call21;
 array[2*256 + 2] = call22;
....
 array[3*256 + 1] = call31;
 array[3*256 + 2] = call32;
....
// Others will be set to null as array is static
}

uint8_t x;
uint8_t y;
index = x*256 + y;
array[index](); // calling appropriate call.

通常,当我看到这样的代码时,我会有点退缩。最糟糕的情况是一个文件,长2.2万行,只有三个函数——这让我哭了。

事实上,在最低级别,你有一系列的条件,这通常意味着涉及某种类型。

所以你的代码看起来有点像:

    If (...) {
       OnTypeConditionOne(...);
     Else if (...) {
       OnTypeConditionTwo(...);
     Else {
       OnTypeConditionThree(...);
     }

显然,您要传递执行子条款所需的任何变量。然后对这些子条款执行同样的操作,直到有了大量的小文件。重要的是要将文件命名为合乎逻辑的名称,否则你可能会迷失在类似的名称中。