优雅的代码逻辑之if else

177 阅读1分钟

你写的代码应该是这样的:
[code 1]

function(){
    if(ignore or error case){
        continue or return; 
    }
    
    //do right logic below ...
    
}

不能这样:
[code 2]

function(){
    if(你认为正确的case的条件){
        //do right logic
        ....
        ...
        ..
        .
    }
    //other logic below ...
    //error or should ignored cases will go here,cause bug
}

为什么?

  1. [code 1]明确拦截:你能明确哪些case被忽略or是错误的,而[code 2]这些错误的cases将会走到后面去,造成bug
  2. [code 1]可扩展性更好:可以扩展处理错误case,【code 2】不可以

所以,我们应该主动去拦截错误or应该被忽略的case,不能让它往下走