[英]How to replace nested if statements with switch statements?
我想使用switch
語句的原因是替換if
語句,因為if
語句太長,但是如何用switch
替換嵌套的if
語句?
算法是這樣的:
if(a very long statement are similar,except the string at the middle)
func1(parameters are same as func1,test1);
if(a very long statement are similar,except the string at the middle)
func2(parameter are same as func1,test2);
.
.
.
if(a very long statement are similar,except the string at the middle)
func16(parameter are same as func1,test16);
我做了以下但有錯誤:
//List initialization...
for (int i = 0; i < list.size(); i++) {
if (statement with list[i] == true) {
switch (list[i]) {
case "test1":
func1(parameter1,test1);
case "test2":
enter code here
func2(parameter1,test2);
case "test3":
func3(parameter1,test3);
.
.
.
case "test16":
func16(parameter1,test16);
}
}
}
我正在使用Java。 任何人都可以給我一些建議。 非常感謝。
在這種情況下,我傾向於接受策略模式,並為每個分支創建一個策略。 界面看起來像這樣:
interface Strategy{
boolean accepts(String value);
void process(String value);
}
你可以使用這樣的東西:
List<Strategy> strategies = // initialize your strategies
list.forEach((item) -> {
strategies.stream()
.filter((s) -> s.accepts(item)) // find the appropriate strategy
.findFirst() // if we found it
.ifPresent(strategy -> strategy.process(item)); // apply it
// or use .getOrElseThrow to fail fast if no strategy can be found
});
關於這一點的好處是每個策略都是可單獨維護和可測試的。 另外:如果你在不同的分支中有類似的代碼,你可以使用一個普通的超類。
顯然,這可以進行優化。 如果您事先知道您期望的字符串,則可以將策略存儲在HashMap中。 如果您只是有一個模糊的想法,也許TreeMap可以提供幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.