简体   繁体   English

具有多个if else和for语句的重构方法

[英]Refactor method with multiple if else and for statements

My method below has code flagged by checkstyle with cyclic complexity = 13 and max allowed is 10: 我的以下方法具有由checkstyle标记的代码,其循环复杂度= 13,允许的最大值为10:

if (typeOfTable.equals("STRING1")) {
    for (String type1Table : tableType1List) {
        if (fileName.contains(metricTable)) {
            tableType= "STRING1";
            return tableType;
        }
    }
} else if (typeOfTable.equals("STRING2")) {
    for (String type2Table : tableType2List) {
        if (fileName.contains(type2Table)) {
            tableType= "STRING2";
            return tableType;
        }
    }
} else if (typeOfTable.equals("STRING3")) {
    if (fileName.contains("String3")) {
        tableType= "STRING3";
        return tableType;
    }
} else if (typeOfTable.equals("STRING4")) {
    if (fileName.contains("String4")) {
        tableType= "STRING4";
        return tableType;
    }
}

Is the best way to rewrite this with switch statements or split into smaller methods, so it meets the CheckStyle requirement? 是使用switch语句重写此代码或将其拆分为较小的方法,使其满足CheckStyle要求的最佳方法吗?

I think there are several options and without knowing your class hierarchy using the Strategy Pattern would be a profound way to implement such behavior. 我认为有几种选择,并且不知道使用策略模式的类层次结构将是实现此类行为的一种深刻方法。

But if you want it quick and dirty you could use an enum and a case statement, eg: 但是,如果您希望它又快又脏,可以使用一个enum和一个case语句,例如:

enum TableType {
    STRING1, STRING2, STRING3;

    public static TableType getType(String typeName) {
        for (TableType type : values()) {
            if (type.name().equals(typeName) {
                return type;
            }
        }

        return STRING1; // if you want a default type
    }
}

and the case statement like this: 和这样的case语句:

TableType tableType = TableType.getType(typeOfTable);
switch(tableType) {
    case STRING1:
       ....
       break;
}

And like already recommended in the comments you should use more functions/methods to reduce the amount of copy-paste-code. 就像注释中已经建议的那样,您应该使用更多的功能/方法来减少复制粘贴代码的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM