我有一个带有千行 if/else 逻辑方法的 java 类,如下所示:
if (userType == "admin") {
if (age > 12) {
if (location == "USA") {
// do stuff
} else if (location == "Mexico") {
// do something slightly different than the US case
}
} else if (age < 12 && age > 4) {
if (location == "USA") {
// do something slightly different than the age > 12 US case
} else if (location == "Mexico") {
// do something slightly different
}
}
} else if (userType == "student") {
if (age > 12) {
if (location == "USA") {
// do stuff
} else if (location == "Mexico") {
// do something slightly different than the US case
}
} else if (age < 12 && age > 4) {
if (location == "USA") {
// do something slightly different than the age > 12 US case
} else if (location == "Mexico") {
// do something slightly different
}
}
我应该如何将其重构为更易于管理的东西?
最佳答案
您应该使用 Strategies ,可能在枚举中实现,例如:
enum UserType {
ADMIN() {
public void doStuff() {
// do stuff the Admin way
}
},
STUDENT {
public void doStuff() {
// do stuff the Student way
}
};
public abstract void doStuff();
}
由于代码中每个最外层 if
分支中的代码结构看起来几乎相同,因此在重构的下一步中,您可能需要使用 template methods 来排除重复项。 .或者,您也可以将位置(可能还有年龄)转变为策略。
更新:在Java4中,可以实现typesafe enum手工,并使用普通的旧子类来实现不同的策略。
关于java - 重构 if/else 逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2913495/