java - 如何用 switch 语句替换嵌套的 if 语句?

标签 java list if-statement linked-list switch-statement

我之所以要使用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。谁能给我一些建议。非常感谢。

最佳答案

在这种情况下,我倾向于采用策略模式,并为每个 if 分支创建一个策略。界面可能如下所示:

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
});

这样做的好处是每个策略都是可以单独维护和测试的。另外:如果您在不同的分支中有类似的代码,则可以使用通用的父类(super class)。

显然,这是可以优化的。如果您预先知道需要什么字符串,则可以将策略存储在 HashMap 中。如果您只有一个模糊的想法,也许 TreeMap 可以提供帮助。

关于java - 如何用 switch 语句替换嵌套的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38266290/

相关文章:

java - 在方法中使用扫描器

java - 通过 jdbc 从 Postgres 列加载 JSON

java - 如何使用 Maven 编写文件?

python - 按值对元组排序,当值相等时使用列表

ruby-on-rails - 如果在Ruby on Rails中如何使用&&?

java - Flink 中的局部变量

javascript - 使用 jquery 向上移动列表项

python - 如何将多个列表实例化为相同的值,尽管在内存中不同?

c++ - 自动生成开关案例。或者另一个建议

javascript - 专注于输入以显示来自 if/if else 条件的控制台日志消息?