【问题标题】:How to reduce the if-else depth?如何减少 if-else 深度?
【发布时间】:2017-10-25 03:51:46
【问题描述】:

我有这个示例代码

public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
    String actionKey;
    if(userAction != null){
        if(currentTaskType != null){
            actionKey = buildKey(currentTaskType, userAction);
            if(dossierActions.containsKey(actionKey)){
                return dossierActions.get(actionKey);
            }
        }

        actionKey = buildKey(anyTaskType(), userAction);
        if(dossierActions.containsKey(actionKey)){
            return dossierActions.get(actionKey);
        }
    }

    return new NullActionProcessor();
}

在这个逻辑中,我有一个映射来通过组合键 TaskType 和 UserAction 存储 ActionProcessable。此方法将返回带有输入 taskType 和操作的 ActionProcessable。 TaskType 可以为 null,所以在这种情况下,我们只需要通过 userAction 获取。

当我通过声纳检查此代码时,它说第三个 if 是“嵌套 if-else 深度为 2(允许的最大值为 1)”

但我不知道如何让它变得更好。 有人给我建议吗?

【问题讨论】:

    标签: coding-style code-cleanup


    【解决方案1】:

    您可以将“if containsKey”部分移出条件以消除代码重复:

    public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
        if (userAction != null) {
            String actionKey = currentTaskType != null
                ? buildKey(currentTaskType, userAction)
                : buildKey(anyTaskType(), userAction);
    
            if (dossierActions.containsKey(actionKey)){
                return dossierActions.get(actionKey);
            }
        }
    
        return new NullActionProcessor();
    }
    

    现在,代码的意图看起来更清晰了(至少对我而言)

    您也可以使第一个条件短路和\或对containsKey 使用三元if,它会删除更多ifs,但会使代码对某些人来说更复杂。

    public static ActionProcessable getActionProcessor(TaskType currentTaskType, UserAction userAction){
        if (userAction == null) { 
            return new NullActionProcessor();
        }
    
        String actionKey = currentTaskType != null
            ? buildKey(currentTaskType, userAction)
            : buildKey(anyTaskType(), userAction);
    
        return dossierActions.containsKey(actionKey)
            ? dossierActions.get(actionKey);
            : new NullActionProcessor();
    }
    

    选择你喜欢的,它们在技术上是相似的。

    由于您没有指定特定的编程语言,还有一点要说:您的代码是空合并运算符用例的一个很好的例子。可悲的是,AFAIK,Java 中没有。在 C# 中,代码可能如下所示:

    public static ActionProcessable GetActionProcessor(TaskType currentTaskType, UserAction userAction) {
        if (userAction == null) { 
            return new NullActionProcessor();
        }
    
        var actionKey = BuildKey(currentTaskType ?? anyTaskType(), userAction);
        return dossierActions[actionKey] ?? new NullActionProcessor();
    }
    

    【讨论】:

    • 谢谢@Yeldar Kurmangaliyev。您的解释对我来说很清楚,我认为代码看起来更简洁明了。我的示例是用 Java 编写的,但也很高兴了解 C#。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-11
    • 2010-12-20
    • 1970-01-01
    • 2019-02-16
    • 2022-12-31
    • 2011-03-06
    相关资源
    最近更新 更多