方法和结构体的设计

2018-02-17  本文已影响0人  李军_6eaa
check 输入参数的有效性
必要时进行防御性的 copies
如何设计好的 method signatures(方法签名)
有哪些方法可以避免过长的参数列表
使用overloading时,要谨慎
List接口中的两个overloadings的remove方法:
remove(E) 和 remove(int)。
由于generics 和 autoboxing 的加入,这两个方法很容易使人迷惑
在使用可变长度参数方法(varargs methods)时,要谨慎
一个方法应该返回 empty collections or arrays, 而不是 nulls
//Returns null to indicate an empty collection. Don't do this
private final List<Cheese> cheesesInStock = ...;
public List<Cheese> getCheeses() {
    return cheesesInStock.isEmpty() ? null
        : new ArrayList<>(cheesesInStock);
}
//The right way to return a possibly empty collection
public List<Cheese> getCheeses() {
    return new ArrayList<>(cheesesInStock);
}
//The right way to return a possibly empty array
public Cheese[] getCheeses() {
    return cheesesInStock.toArray(new Cheese[0]);
}
// Optimization - avoids allocating empty collections
public List<Cheese> getCheeses() {
    return cheesesInStock.isEmpty() ? Collections.emptyList()
        : new ArrayList<>(cheesesInStock);
}
// Optimization - avoids allocating empty arrays
private static final Cheese[] EMPTY_CHEESE_ARRAY = new Cheese[0];

public Cheese[] getCheeses() {
    return cheesesInStock.toArray(EMPTY_CHEESE_ARRAY);
}
一个方法返回optionals时,要谨慎
如果一个方法不能返回一个value,有哪些处理方法?
对于所有exposed API elements, 写doc comments
/**
 * 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 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);
上一篇下一篇

猜你喜欢

热点阅读