個人讀書筆記熄诡,部分沒讀懂的知識點(diǎn)可能會簡單概括或缺失,以后反復(fù)閱讀后再完善凰浮。
第7章 方法
第38條: 檢查參數(shù)的有效性
非公有的方法通常應(yīng)該使用斷言檢查它們的參數(shù)袜茧。
private static void sort(long a[], int offset, int length) {
assert a != null;
assert offset >=0&& offset<=a.length;
assert length >= 0 && length <= a.length - offset;
}
斷言失敗將會拋出AssertionError。
第39條: 必要時進(jìn)行保護(hù)性拷貝
保護(hù)性拷貝(defensive copy):
public Period(Date start, Date end) {
/*if (start.compareTo(end) > 0) {
throw new IllegalArgumentException(start + "after" + end);
}
this.start=start;
this.end=end;*/
//Date本身可變纳鼎,所以上訴寫法很容易違反約束條件裳凸。
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (this.start.compareTo(this.end) > 0) {
throw new IllegalArgumentException(start + "after" + end);
}
}
保護(hù)性拷貝是在檢查參數(shù)的有效性之前進(jìn)行的,并且有效性檢查是針對拷貝之后的對象逗宁。
第40條: 謹(jǐn)慎設(shè)計方法簽名
謹(jǐn)慎選擇方法的名稱
遵循標(biāo)準(zhǔn)的命名習(xí)慣(第56條)
不要過于追求提供便利的方法
一項(xiàng)操作經(jīng)常用到時才考慮為它提供快捷方式梦湘。
避免過長的參數(shù)列表
縮短參數(shù)列表的方法:
1、把方法分解成多個方法哼拔。
2禁灼、創(chuàng)建輔助類。
3僻孝、從對象構(gòu)建到方法調(diào)用都采用Builder模式守谓。
第41條: 慎用重載
不要導(dǎo)出兩個具有相同參數(shù)數(shù)目的重載方法斋荞。
Java出了自動裝箱和泛型后荞雏,重載的使用就需要更加謹(jǐn)慎了。
例子:
public class SetList {
public static void main(String[] args) {
Set<Integer> set = new TreeSet<>();
List<Integer> list = new ArrayList<>();
for (int i = -3; i < 3; i++) {
set.add(i);
list.add(i);
}
for (int i = 0; i < 3; i++) {
set.remove(i);
//這里i被自動裝箱到Integer中。程序不會從集合中去除正值
//列表去除的是從哪個位置開始
//list.remove( i);
list.remove((Integer)i);
}
System.out.println(set + " " + list);
}
}
第42條: 慎用可變參數(shù)
在重視性能的情況下凤优,聲明該方法的5個重載悦陋。當(dāng)參數(shù)的數(shù)目超過3個時,就使用一個可變參數(shù)方法筑辨。
public Foo() {}
public Foo(int a1) {}
public Foo(int a1, int a2) {}
public Foo(int a1, int a2, int a3) {}
public Foo(int a1, int a2, int a3, int... rest) {}