如何避免if else

作者: 就是lpc | 来源:发表于2018-04-02 17:17 被阅读366次

    如何避免if else

    问题

    刚在看到这个问题的时候。我不假思索的回了一句if return不就行了嘛。后来才知道,这个问题的问的不是这么简单。确实if return是一个很好的编码习惯。但是当我们遇到一些业务场景比如:

    - (void)needDoSomethingWithErrorCode:(NSInteger)errorCode{
        if (errorCode == 0) {
            //任务1
        }else if (errorCode == 2){
            //任务2
        }else if (errorCode == 3){
            //任务3
        }..
    }
        
    

    或者我们可能这样写

    - (void)needDoSomethingWithErrorCode:(NSInteger)errorCode{
        switch (errorCode) {
            case 0:
                //任务1
                break;
            case 1:
                //任务2
                break;
            case 2:
                break;
                //任务3
                ...
            default:
                break;
        }
    }
    
    

    这样写有问题吗?满足正常的开发是没有问题的。但是当需要加一个分支逻辑就必须得去if else结构中改代码,这样不利于程序扩展,同时也非常难维护,如果业务复杂到一定的程度这块代码可能没法去重构了。

    解决方法

    回到刚才那个问题如何避免if else,我觉得这个题目应该有很多的答案。我的if return不见得就是错误的……(o^^o),不过 这个问题应该是问我们一种架构思想。

    - (void)needDoSomethingWithErrorCode:(NSInteger)errorCode{
        [self dealWithErrorCode:errorCode];
    }
    
    - (void)dealWithErrorCode:(NSInteger)errorCode{
        NSString *methodString = @"dealWithErrorCode";
        methodString = [methodString stringByAppendingPathExtension:[NSString stringWithFormat:@"%0.0ld",(long)errorCode]];
        SEL method = NSSelectorFromString(methodString);
        if ([self respondsToSelector:method]) {
            [self performSelector:method withObject:nil];
        }else{
            [self dealWithNoDefineErrorCode:errorCode];
        }
    }
    
    //处理错误类型0
    - (void)dealWithErrorCode0{
        NSLog(@"//处理错误类型0");
    }
    //处理错误类型1
    - (void)dealWithErrorCode1{
        NSLog(@"//处理错误类型1");
    }
    //未定义的方法类型
    - (void)dealWithNoDefineErrorCode:(NSInteger)errorCode{
        NSLog(@"//未定义的方法类型");
    }
    

    这样的写法的好处就是之后要新增新的方法就可以,不需要去处理needDoSomethingWithErrorCode这个函数。
    通过反射和简单的工厂模式,或者是策略模式去设计我们的代码。可以让我们避免使用一些臃肿的if else

    相关文章

      网友评论

        本文标题:如何避免if else

        本文链接:https://www.haomeiwen.com/subject/aluxhftx.html