第38条 检查参数的有效性
绝大多数方法或者构造器都有参数限制,有必要在方法执行之前对参数进行检查
public BigInteger mod(BigInteger m) {
if (m.signum() <= 0)
throw new ArithmeticException("Modulus <= 0: " + m);
... //Do the computation.
}
还有一种是用断言来检查参数,如果断言失败,将会抛出AssertionErroe
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);
... //Do the computation
}
还有些例外情况,如检查工作代价昂贵或者不切实际,或者检查工作已经在其他地方完成了。用Collections.sort(List)来为一个对象列表排序的时候,sort方法会去检查这些对象是否可以比较,不能就会抛出ClassCastException,所以我们就不用重复这些工作了。
第39条 必要时进行保护性拷贝
如果累具有从客户端得到或者返回到客户端的可变组件,类就必须保护性地拷贝这些组件。如果拷贝的成本收到限制,并且类信任它的客户端不会不恰当地修改组件,就可以在文档中指明客户端的职责是不得修改受到影响的组件,以此来代替保护性拷贝。 保护性拷贝的列子可以看这http://blog.csdn.net/tounaobun/article/details/8607174
第40条 慎用设计方法签名
方法名称应该遵循命名规则且易理解。方法应该是功能齐全(通用),只有当一项操作经常用到的时候,才考虑为它提供快捷方式。
参数不能过长,有三种方法可以缩短过长的参数列表:1、把方法分解成多个方法 2、创建辅助类来保存参数的分组 3、对象构造到方法调用都用Builder模式
对于参数类型,要优先使用接口而不是类,这样提高了更改灵活性
对于boolean参数,要优先使用两个元素的枚举类型
第41条 慎用重载
能够重载方法”并不意味着就“应该重载方法”。一般情况下,对于多个具有相同参数数目的方法来说,应该尽量避免重载方法。至少应该避免这样的情形:同一组参数只需经过类型转换就可以被传递给不同的重载方法。
第42条 慎用可变参数
对于可变参数,建议用这种方法来写,
static int min(int firstArg,int...remainingArgs) {
int min = firstArgs;
for (int arg : remainingArgs) {
if (arg < min)
min = arg;
}
return min;
}
有的时候在重视性能的情况下,使用可变参数机制要特别小心。可变参数方法的每次调用都会导致进行一次数组分配和初始化。如果确定确实无法承受这一成本,但又需要可变参数的灵活性,还有一种模式可以弥补这一不足。假设确定对某个方法95%的调用会有3个或者更少的参数,就声明该方法的5个重载,每个重载方法带有0个至3个普通参数,当参数的数目超过3个时,就使用一个可变参数方法:
public void foo() {}
public void foo(int a1) {}
public void foo(int a1, int a2) {}
public void foo(int a1,int a2,int a3) {}
public void foo(int a1,int a2,int a3,int...rest) {}
第43条 返回零长度的数组或者集合,而不是null
第44条 为所有导出的API元素编写文档注释
为了完整地描述方法的约定,方法的文档注释应该让每个参数都有一个@param标签,以及一个@return标签(除了返回类型为void),以及对于该方法抛出的每个异常,
都有一个@throws标签。如下:
/**
* Returns the element at the specified position in this list.
*
* <p>This method is <i>not</i> guaranteed to run in constant
* time.In some implementations it may run in time proportional
* to the element position.
*
* @param index of element to return:must be
* non-negative and less than the size of this list
* @return the element at the specified position in this list
* @throws IndexOutOfBoundsException if the index is out of range
* ({@code index < 0 || index >= this.size()})
*/
E get(int index);