if-else 重构

最近发现自己写的代码if else太多了,有时候自己回头看都要重新捋逻辑,很不好。决定深入理解下if else重构。

中心思想:

①不同分支应当是同等层次,内容相当。

②合并条件表达式,减少if语句数目。

③减少嵌套,减少深层次逻辑。

④尽可能维持正常流程代码在外层。

⑤减少使用临时变量。

⑥尽早return!

例子:

①异常逻辑处理。

public int getResult(int a, int b, int c){
        int result = 0;
        if ( a > 0){
            if(b > 0 && c >0 ){
                result = a * b * c;
            }
        }
        return result;
    }

    public int getResult2(int a, int b, int c){
        if (a < 0){
            return 0;
        }
        if (b <= 0 || c <= 0){
            return  0;
        }
        return a * b * c;
    }

两种方式结果是一样的,这里重构的思想是:

1.首先减少深层嵌套,将if里的if提出来。

2.然后将非正常的情况放在最前面,并直接return。

② 异常逻辑处理2

int getResult(){
    int result;
    if(caseA) {
        result = functionA();
    }else{
        if(caseB){
            result = functionB();
        }
        else{
            if(caseC){
                result = functionC();
            else{
                result = normarlFunction();
            }
        }
    }
    return result;
}

判断内层if和顶层有没有关联,如果没有关联,直接提取。

int getResult(){
    if(caseA) 
        return functionA();
 
    if(caseB)
        return functionB();
 
    if(caseC)
        return functionC();
 
    return normarlFunction();
}

 

 

 

③ 分支处理

int getResult(){
    int c= 0;
    if (type == 1) {
        a = b;
        c = a * b - b + a;
    }
    else if (type == 2) {
        b = b + a;
        c = a * b * (b + a);
    }
return c; }

这里if else 内部处理函数会影响阅读体验,可以将内部处理方法提出来,并直接return。

int getResult(){
    
    if (type == 1) {
        return gerResult1(b, c);
    }
    else if (type == 2) {
        return getResult2(b, c);
    }
}
 
int gerResult1(int a, int b){
    a = b;
    return (a * b - b + a);
}
 
int getResult2(int a, int b){
    b = b + a;
    return a * b - b + a;
}

④多重分支

int getResult(){
    if(caseA){
        return funcA();
    }
    else if(caseB){
        return funcB();
    }
    else if(caseC){
        return funcC();
    }
    else if(caseD){
        return funcD();
    }
    else if(caseE){
        return funcE();
    }
}

如果情况限定必须有多个分支,可以改外用map实现,极大提高可阅读性。

int getResult(){
    Map<String, Object> resultMap = new HashMap();
    resultMap.put(caseA, functionA());
    resultMap.put(caseB, functionB());
    resultMap.put(caseC, functionC());
    resultMap.put(caseD, functionD());
    resultMap.put(caseE, functionE());
    return resultMap.get(case);
}

 

转载于:https://www.cnblogs.com/lizhang4/p/9950745.html

### 如何优化或重构复杂的 if-else 代码结构 #### 使用公共函数封装逻辑 一种常见的方法是将 `if-else` 内部的复杂逻辑提取到独立的函数中。这种方法能够显著提升代码可读性和维护性,因为每个条件分支的功能都被清晰地定义在一个单独的单元中[^1]。 ```python def handle_condition_a(): pass # 实现 A 条件下的处理逻辑 def handle_condition_b(): pass # 实现 B 条件下的处理逻辑 condition = get_condition() if condition == 'A': handle_condition_a() elif condition == 'B': handle_condition_b() ``` #### 利用数据结构替代分支语句 另一种有效的方式是利用字典或其他映射型数据结构来代替传统的 `if-else` 分支判断。这种方式不仅简化了代码结构,还提高了运行效率,尤其是在多个状态需要被频繁切换的情况下[^2]。 ```python handlers = { 'A': lambda: print("Handling Condition A"), 'B': lambda: print("Handling Condition B"), } condition = get_condition() handler = handlers.get(condition, lambda: print("Unknown Condition")) handler() ``` #### 应用设计模式解决复杂场景 对于更加复杂的业务逻辑,可以考虑引入面向对象的设计模式,例如 **策略模式** 或 **状态模式**。这些模式的核心思想在于通过多态机制动态调整行为,从而彻底摆脱冗长的嵌套 `if-else` 结构。 以下是基于策略模式的一个简单例子: ```java interface Strategy { void execute(); } class ConcreteStrategyA implements Strategy { @Override public void execute() { System.out.println("Executing strategy A"); } } class ConcreteStrategyB implements Strategy { @Override public void execute() { System.out.println("Executing strategy B"); } } public class Context { private Strategy strategy; public void setStrategy(Strategy strategy) { this.strategy = strategy; } public void run() { strategy.execute(); } } ``` #### 函数式编程风格的应用 如果项目允许采用现代语言特性,则可以通过函数式编程手段进一步精简代码。例如,在支持高阶函数的语言中,可以直接传递回调函数作为参数,甚至完全移除显式的控制流语句[^3]。 ```javascript const strategies = { a: () => console.log('Processing case A'), b: () => console.log('Processing case B') }; function process(input) { (strategies[input] || (() => console.error(`Invalid input ${input}`)))(); } process('a'); // 输出 Processing case A process('z'); // 输出 Invalid input z ``` ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值