过长的消息链
想要摆脱初级程序员的水平,首先需要减少暴露细节
迪米特法则
- 每个单元只能对与他有紧密关系的单元,拥有有限的知识
- 每个单元只能和朋友交谈,不与陌生人交谈
- 每个单元只能和自己最直接的朋友交谈
案例1
1
| String name = book.getAuthor().getName();
|
修正方式:隐藏委托关系,即把调用封装起来
1 2 3 4 5 6 7 8 9 10 11
| class Book { ... public String getAuthorName() { return this.author.getName(); } ... }
String name = book.getAuthorName();
|
基本类型偏执
重构手法:以对象取代基本类型
1 2 3 4
| public double getEpubPrice(final boolean highQuality, final int chapterSequence) { ... }
|
问题:虽然价格是用浮点数在存储,但是价格和浮点数本身并不是同一个概念。
需求1:
价格大于0,如果使用了double来存储,你会怎么限制呢?通常会这样
1 2 3
| if (price <= 0) { throw new IllegalArgumentException("Price should be positive"); }
|
这种校验会是很多场景都需要的,因此类似的逻辑需要大量去重复的写。
假设这里引入了price模型会是怎样呢?
1 2 3 4 5 6 7 8 9 10 11
| class Price { private long price; public Price(final double price) { if (price <= 0) { throw new IllegalArgumentException("Price should be positive"); } this.price = price; } }
|
这样校验就可以放在初始化的时候进行了。
这种手法叫做对象取代基本模型。
需求2:
假设我们希望价格对外只呈现2位。
没有price这个模型的话 ,依旧会是散布在代码的各个地方,一旦有了这个模型,代码就简单多了
1 2 3 4
| public double getDisplayPrice() { BigDecimal decimal = new BigDecimal(this.price); return decimal.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); }
|