一. 前言
在实际业务开发中,常常面临多个条件判断的情况,如果不加思索就写代码,很容易出现一堆if else 的代码,导致代码逻辑不清晰,可阅读性很差。我们经藏会在项目中见到大片大片的if else,给后来人带来很大的理解成本。
过多的if else ,这是很明显的坏代码的味道,这时就应该考虑自己的设计是否合理,有没有更好的表达方式了。
本文主要包含三块内容:
- 垃圾代码展示
- 优化上述垃圾代码
- 分析,同时介绍了下开源框架Dubbo中模板模式如何使用
二. 实战
下面是一个最常见的不同等级的用户采用不同的处理方法的例子
- 普通用户需要收取运费,运费是商品价格的 10%,无商品折扣;
- VIP 用户同样需要收取商品价格 10% 的快递费,但购买两件以上相同商品时,第三件开始享受一定折扣;
- 内部用户可以免运费,无商品折扣。
代码实现也很简单,使用 if/else来判断不同的用户等级,然后分别进行处理。
//购物车
@Data
public class Cart {
//商品清单
private List<Item> items = new ArrayList<>();
//总优惠
private BigDecimal totalDiscount;
//商品总价
private BigDecimal totalItemPrice;
//总运费
private BigDecimal totalDeliveryPrice;
//应付总价
private BigDecimal payPrice;
}
//购物车中的商品
@Data
public class Item {
//商品ID
private long id;
//商品数量
private int quantity;
//商品单价
private BigDecimal price;
//商品优惠
private BigDecimal couponPrice;
//商品运费
private BigDecimal deliveryPrice;
}
public class UserCart {
public Cart process(long userId, Map<Long, Integer> items) {
Cart cart = new Cart();
//把Map的购物车转换为Item列表
List<Item> itemList = new ArrayList<>();
items.entrySet().stream().forEach(entry -> {
Item item = new Item();
item.setId(entry.getKey());
item.setPrice(Db.getItemPrice(entry.getKey()));
item.setQuantity(entry.getValue());
itemList.add(item);
});
cart.setItems(itemList);
//根据用户ID获得用户类型
String userCategory = Db.getUserCategory(userId);
//普通用户购物车处理
if(userCategory.equals("Normal")){
itemList.stream().forEach(item -> {
//运费为商品总价的10%