常见的代码:当你必须得先了解一个类的细节,才能写出代码时,这只能说明一件事,这个封装是失败的
//过长的消息链
String name = book.getAuthor().getName();
//隐藏委托关系,将调用封装起来
class Book {
...
public String getAuthorName() {
return this.author.getName();
}
...
}
String name = book.getAuthorName();
基本类型偏执问题
//虽然价格本身是用浮点数在存储,但价格和浮点数本身并不是同一个概念,有着不同的行为需求。比如,
//一般情况下,我们要求商品价格是大于 0 的,但 double 类型本身是没有这种限制的
public double getEpubPrice(final boolean highQuality, final int chapterSequence) {
...
}
//这种较验就得各个地方都得写了
if (price <= 0) {
throw new IllegalArgumentException("Price should be positive");
}
//采用以对象取代基本数据类型,将较验放在对象初始化的时候进行
class Price {
private long price;
public Price(final double price) {
if (price <= 0) {
throw new IllegalArgumentException("Price should be positive");
}
this.price = price;
}
}