重构 if else 分支的最佳方法是什么
What is the best way to refactor an if else branch
我有一个 if-else 分支,例如
if(name.contains(substring)){
if(name.contains(substring1)){
return "this";
}else if(name.contains(substring2)){
return "that";
}
...
}else if(){
// if else ladder
}
....//else if ladder continues
else{
return "them"
}
重构它的最佳方法是什么?那这样的逻辑最有效的方法是什么?
你可以用switch语句代替else if ladder。由于编译器能够优化 switch 语句,因此它们通常被认为效率更高。
过多的 if/else
或 switch
语句可能表示设计不佳。
在某些情况下,使用接口(多态性)可能会更好,例如 Replace Conditional with Polymorphism。
当然不是所有的if
都是不必要的。但最好避免将控制结构与尽可能多的工作混为一谈。最后,代码应该易于阅读。
我有一个 if-else 分支,例如
if(name.contains(substring)){
if(name.contains(substring1)){
return "this";
}else if(name.contains(substring2)){
return "that";
}
...
}else if(){
// if else ladder
}
....//else if ladder continues
else{
return "them"
}
重构它的最佳方法是什么?那这样的逻辑最有效的方法是什么?
你可以用switch语句代替else if ladder。由于编译器能够优化 switch 语句,因此它们通常被认为效率更高。
过多的 if/else
或 switch
语句可能表示设计不佳。
在某些情况下,使用接口(多态性)可能会更好,例如 Replace Conditional with Polymorphism。
当然不是所有的if
都是不必要的。但最好避免将控制结构与尽可能多的工作混为一谈。最后,代码应该易于阅读。