如何避免过多嵌入if-else
How to avoid too much embedded if-else?
如下:
if(...){
if(...){
}else{
...
}
}else if(...){
if(...){
}else{
...
}
}else{
...
}
在编码中总是遇到这种情况,它看起来太可怕了。如何避免?
没有一般规则。但是,两种常见的情况是:
- 当切换/案例可以帮助您减少代码量时
- 当您应该使用状态机来设计代码时
根据您的需要和代码,这些可能是更好的解决方案。
假设:您希望根据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(...);
}
显然,您要传递执行子条款所需的任何变量。然后对这些子条款执行同样的操作,直到有了大量的小文件。重要的是要将文件命名为合乎逻辑的名称,否则你可能会迷失在类似的名称中。
相关文章:
- 我的简单if-else语句是如何无法访问的代码
- 如何删除peer if else分支中的冗长句子
- 我似乎对if/else的基本语句有问题:/
- 使用if-else将数字转换为单词
- 为什么这个案例陈述需要一个"if else"而不仅仅是一个"if"?
- C++ If/Else 语句被跳过
- 如果条件不相关,我应该更喜欢两个 if 语句而不是 if-else 语句吗?
- 如何将 if else 语句重写为 switch 语句
- 在 C++ 中的 if-else if- else 语句期间更改变量
- 为什么我的 if else 语句不起作用并从数组中输出正确的索引?
- 我的 If Else 语句无法在向量 (C++) 中提供最大值
- 具有嵌套 if-else 的循环的时间复杂度
- 为什么无论输入如何,所有 if-else 语句都会打印?
- 简化对两个布尔值的 4 个 if/else 检查
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 如何避免使用多个if-else来检查返回值是否为错误代码?
- 避免在字符串中分支 if-else 以类型调度
- 避免使用模板功能的IF-ELSE语句
- 如何避免过多嵌入if-else
- 初学者c++避免重复if/else if语句