重构 if/else 逻辑 [英] Refactoring if/else logic

查看:25
本文介绍了重构 if/else 逻辑的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有千行 if/else 逻辑方法的 java 类,如下所示:

I have a java class with a thousand line method of if/else logic like this:

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

我应该如何将其重构为更易于管理的内容?

How should I refactor this into something more managable?

推荐答案

你应该使用策略, 可能在枚举中实现,例如:

You should use Strategies, possibly implemented within an enum, e.g.:

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 分支中的代码结构看起来几乎相同,在重构的下一步中,您可能希望使用 模板方法.或者,您也可以将位置(也可能是年龄)转变为策略.

As the code structure within each outermost if branch in your code looks pretty much the same, in the next step of refactoring you might want to factor out that duplication using template methods. Alternatively, you might turn Location (and possibly Age) into a strategy as well.

更新: 在 Java4 中,您可以实现一个 手动类型安全枚举,并使用普通的旧子类来实现不同的策略.

Update: in Java4, you can implement a typesafe enum by hand, and use plain old subclassing to implement the different strategies.

这篇关于重构 if/else 逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆