我的方法下面的代码标记为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要求吗?
答案 0 :(得分:0)
我认为有几种选择,如果不了解使用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;
}
就像评论中已经建议的那样,你应该使用更多的函数/方法来减少复制粘贴代码的数量。