java - 重构 if/else 逻辑

标签 java refactoring if-statement

我有一个带有千行 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/

相关文章:

java - JMSListener - 动态选择器

ruby-on-rails - `new` 关键字在此 Ruby 方法定义中如何工作?

eclipse - 我可以在 Eclipse 中禁用重构预览吗?

java - 比较两个时间值

php - MySQL 如果存在更新值,否则插入

java - 将对象列表转换为 Long 列表

java - 使用 JGraphx 在 xml 文件中保存和加载图形

java - 如何在android studio中停止计时器,然后从停止时重新开始?

c++ - 尝试(稍微)概括 C++ 模板。关联容器 key :Value Inversion

java - if jsp中的条件不起作用