如何最优简化这段嵌套代码?需调用两个不同默认分支
嵌套分支代码的最优简化方案
现有如下嵌套代码片段,需调用两个不同的默认分支。尝试过switch贯穿语句优化,但效果仍不理想,希望获取最优的代码简化方案。
注:此代码非本人编写。
原代码
if( auto id:{k_b0,k_b1}){ auto baseIndex = 0; auto count = false; if(!rmt){ switch(src){ case a: {if(slow) {count = Getconfig(); baseindex =0;} else {count = GetslowConfig(); baseindex =4;}}break; case b: {if(slow) {count = Getconfig(); baseindex =0;} else {count = GetslowConfig(); baseindex =4;}}break; case c: {if(slow) {count = Getconfig(); baseindex =0;} else {count = GetslowConfig(); baseindex =4;}}break; default : count = GetdefaultConfigone(); break; } }else{ switch(src){ case a: {if(slow) {count = Getconfigrmt(); baseindex =1;} else {count = GetslowConfigrmt(); baseindex =5;}}break; case b: {if(slow) {count = Getconfigrmt(); baseindex =1;} else {count = GetslowConfigrmt(); baseindex =5;}}break; case c: {if(slow) {count = Getconfigrmt(); baseindex =1;} else {count = GetslowConfigrmt(); baseindex =5;}}break; default : count = GetdefaultConfigtwo(); break; } } sample(baseindex, count, id); }
优化方案
核心优化思路
原代码的冗余点集中在:src为a/b/c时的分支逻辑完全重复,仅rmt状态会影响调用的函数和baseIndex值。优化方向是合并重复分支,将状态判断与配置获取解耦。
基础简化版
直接合并a/b/c的分支判断,消除重复的switch结构:
if (auto id : {k_b0, k_b1}) { auto baseIndex = 0; auto count = false; // 合并a/b/c的分支判断 const bool isABC = (src == a || src == b || src == c); if (isABC) { if (!rmt) { if (slow) { count = Getconfig(); baseIndex = 0; } else { count = GetslowConfig(); baseIndex = 4; } } else { if (slow) { count = Getconfigrmt(); baseIndex = 1; } else { count = GetslowConfigrmt(); baseIndex = 5; } } } else { // 直接根据rmt选择默认配置 count = rmt ? GetdefaultConfigtwo() : GetdefaultConfigone(); } sample(baseIndex, count, id); }
可扩展优化版(映射表实现)
如果后续可能新增状态组合,用映射表将状态与配置绑定,提升代码可维护性:
// 定义配置映射结构体,统一存储配置函数和baseIndex struct ConfigMapping { bool(*getConfigFunc)(); int baseIndex; }; // 预定义所有状态组合对应的配置映射 const ConfigMapping configMap[2][2] = { // !rmt 状态下:slow=true, slow=false { {Getconfig, 0}, {GetslowConfig, 4} }, // rmt 状态下:slow=true, slow=false { {Getconfigrmt, 1}, {GetslowConfigrmt, 5} } }; if (auto id : {k_b0, k_b1}) { auto baseIndex = 0; auto count = false; const bool isABC = (src == a || src == b || src == c); if (isABC) { // 通过状态索引直接获取对应配置 const auto& mapping = configMap[rmt][slow]; count = mapping.getConfigFunc(); baseIndex = mapping.baseIndex; } else { count = rmt ? GetdefaultConfigtwo() : GetdefaultConfigone(); } sample(baseIndex, count, id); }
优化说明
- 基础简化版直接消除了重复的switch-case结构,代码行数减少,可读性大幅提升
- 映射表版本将状态组合与配置逻辑完全解耦,后续新增状态或修改配置时,只需调整映射表即可,无需修改分支判断逻辑,扩展性更强
内容的提问来源于stack exchange,提问作者Zazy
相关产品推荐
相关产品推荐

