一 提前return,去除不必要的else
- 优化前:
if (condition) { //doSomething } else { return; }
- 优化后:
if(!condition){ return; } //doSomething
二 使用条件三目运算符
- 优化前:
int price; if (condition) { price = 80; } else { price = 100; }
- 优化后:
int price = condition ? 80 : 100;
三 使用枚举
它也可以看作一种表驱动方法
- 优化前:
String OrderStatusDes; if (orderStatus == 0) { OrderStatusDes = "订单未支付"; } elseif ( OrderStatus == 1 ) { OrderStatusDes = "订单已支付"; } elseif ( OrderStatus == 2 ) { OrderStatusDes = "已发货"; } ...
- 优化后:
public enum OrderStatusEnum { UN_PAID(0, "订单未支付"), PAIDED(1, "订单已支付"), SENDED(2, "已发货"); private int index; private String desc; public int getIndex() { return index; } public String getDesc() { return desc; } OrderStatusEnum(int index, String desc) { this.index = index; this.desc = desc; } OrderStatusEnum of(int orderStatus) { for (OrderStatusEnum temp : OrderStatusEnum.values()) { if (temp.getIndex() == orderStatus) { return temp; } } return null; } }
String OrderStatusDes = OrderStatusEnum.0f(orderStatus).getDesc();
public enum Week { SUNDAY(7){ @Override public void getWeekNum() { System.out.println(7); } }, MONDAY(1) { @Override public void getWeekNum() { System.out.println("星期一"); } }, TUESDAY(2){ @Override public void getWeekNum() { System.out.println("礼拜二"); } }, WEDNESDAY(3){ @Override public void getWeekNum() { System.out.println("周三"); } }; Week(int index) { this.index = index; } private int index; public abstract void getWeekNum(); }
Week.TUESDAY.getWeekNum();
四 表驱动
- 优化前:
if (param.equals(value1)) { doAction1(someParams); } else if (param.equals(value2)) { doAction2(someParams); } else if (param.equals(value3)) { doAction3(someParams); } // ...
- 优化后:
Map<?, Function<?> action> actionMappings = new HashMap<>(); // 这里泛型 ? 是为方便演示,实际可替换为你需要的类型 // When init actionMappings.put(value1, (someParams) -> { doAction1(someParams)}); actionMappings.put(value2, (someParams) -> { doAction2(someParams)}); actionMappings.put(value3, (someParams) -> { doAction3(someParams)}); // 省略 null 判断 actionMappings.get(param).apply(someParams);
五 合并条件表达式
- 优化前
double getVipDiscount () { if (age < 18) { return 0.8; } if ("深圳".equals(city)) { return 0.8; } if (isStudent) { return 0.8; } //do somethig }
- 优化后
double getVipDiscount(){ if (age< 18 || "深圳".equals(city)||isStudent){ return 0.8; } //doSomthing }
六 使用 Optional
- 优化前:
String str = "jay@jim"; if (str != null) { System.out.println(str); } else { System.out.println("Null"); }
- 优化后:
Optional<String> strOptional = Optional.of("jay@jim"); strOptional.ifPresentOrElse(System.out::println, () -> System.out.println("Null"));
七 优化逻辑结构,让正常流程走主干
- 优化前:
public double getAdjustedCapital () { if (_capital <= 0.0) { return 0.0; } if (_intRate > 0 && _duration > 0) { return (_income / _duration) * ADJ_FACTOR; } return 0.0; }
- 优化后:
public double getAdjustedCapital () { if (_capital <= 0.0) { return 0.0; } if (_intRate <= 0 || _duration <= 0) { return 0.0; } return (_income / _duration) * ADJ_FACTOR; }
将条件反转使异常情况先退出,让正常流程维持在主干流程,可以让代码结构更加清晰
八 策略模式+工厂方法
需求,根据不同勋章类型,处理相对应的勋章服务,优化前有以下代码:
String medalType = "guest"; if ("guest".equals(medalType)) { System.out.println("嘉宾勋章"); } else if ("vip".equals(medalType)) { System.out.println("会员勋章"); } else if ("guard".equals(medalType)) { System.out.println("展示守护勋章"); } ...
首先,我们把每个条件逻辑代码块,抽象成一个公共的接口,可以得到以下代码:
//勋章接口 public interface IMedalService { void showMedal (); String getMedalType (); }
我们根据每个逻辑条件,定义相对应的策略实现类,可得以下代码:
//守护勋章策略实现类 public class GuardMedalServiceImpl implements IMedalService { @Override public void showMedal() { System.out.println("展示守护勋章"); } @Override public String getMedalType() { return "guard"; } }
//嘉宾勋章策略实现类 public class GuestMedalServiceImpl implements IMedalService { @Override public void showMedal() { System.out.println("嘉宾勋章"); } @Override public String getMedalType() { return "guest"; } }
//VIP勋章策略实现类 public class VipMedalServiceImpl implements IMedalService { @Override public void showMedal() { System.out.println("会员勋章"); } @Override public String getMedalType() { return "vip"; } }
接下来,我们再定义策略工厂类,用来管理这些勋章实现策略类,如下:
//勋章服务工产类 public class MedalServicesFactory { private static final Map<String, IMedalService> map = new HashMap<>(); static { map.put("guard", new GuardMedalServiceImpl()); map.put("vip", new VipMedalServiceImpl()); map.put("guest", new GuestMedalServiceImpl()); } public static IMedalService getMedalService(String medalType) { return map.get(medalType); } } ...
使用了策略+工厂模式之后,代码变得简洁多了,如下:
public class Test { public static void main(String[] args) { String medalType = "guest"; IMedalService medalService = MedalServicesFactory.getMedalService(medalType); medalService.showMedal(); } }
九 职责链模式
- 重构前
public void handle(request) { if (handlerA.canHandle(request)) { handlerA.handleRequest(request); } else if (handlerB.canHandle(request)) { handlerB.handleRequest(request); } else if (handlerC.canHandle(request)) { handlerC.handleRequest(request); } }
- 重构后
public void handle(request) { handlerA.handleRequest(request); } public abstract class Handler { protected Handler next; public abstract void handleRequest(Request request); public void setNext(Handler next) { this.next = next; } } public class HandlerA extends Handler { public void handleRequest(Request request) { if (canHandle(request)) doHandle(request); else if (next != null) next.handleRequest(request); } }