[英]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。 由于编译器能够优化 switch 语句,因此通常认为它们更有效。
过多的if/else
或switch
语句可能表明设计不佳。
在某些情况下,最好使用接口(多态性),例如Replace Conditional with Polymorphism 。
当然不是所有的if
都是不必要的。 但最好避免将控制结构与工作混为一谈。 最后,代码应该易于阅读。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.