下面的方法具有由 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;
}
}
最好的方法是使用 switch 语句重写它或拆分为更小的方法,从而满足 CheckStyle 要求吗?
最佳答案
我认为有几个选项,并且不知道您的类层次结构使用 Strategy Pattern将是实现这种行为的一种深刻的方式。
但是如果您希望它快速而肮脏,您可以使用 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
}
}
案例陈述如下:
TableType tableType = TableType.getType(typeOfTable);
switch(tableType) {
case STRING1:
....
break;
}
就像评论中已经建议的那样,您应该使用更多函数/方法来减少复制粘贴代码的数量。
关于java - 使用多个 if else 和 for 语句重构方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28042920/