方法和結(jié)構(gòu)體的設(shè)計(jì)

check 輸入?yún)?shù)的有效性
  • index values 必須是非負(fù)的,object references 必須是 non-null,可以使用 Objects.requireNonNull
  • 在方法體的開(kāi)始處 check 輸入?yún)?shù)的有效性,這樣便于快速失敗,并拋出合適的exception
必要時(shí)進(jìn)行防御性的 copies
  • Date 類過(guò)時(shí)了,不應(yīng)該在新代碼中使用;可以考慮使用 Instant 或者
    Local-DateTime 或者 ZonedDateTime
如何設(shè)計(jì)好的 method signatures(方法簽名)
  • 遵守命名規(guī)則
  • 避免過(guò)長(zhǎng)的方法名
  • 避免過(guò)長(zhǎng)的參數(shù)列表
  • 方法的類型優(yōu)先使用接口,而不是具體類
  • 相對(duì)于boolean參數(shù),優(yōu)先使用two-element enum 類型
有哪些方法可以避免過(guò)長(zhǎng)的參數(shù)列表
  • 拆分成多個(gè)子方法
  • 創(chuàng)建一個(gè)包含這些參數(shù)的help類
  • 采用Builder模式
使用overloading時(shí),要謹(jǐn)慎
  • overloaded 方法是在編譯期確定的,overridden 方法是在運(yùn)行期確定的
  • 不要導(dǎo)出具有相同參數(shù)個(gè)數(shù)的兩個(gè)overloadings方法,尤其是通過(guò)casts可以互相轉(zhuǎn)換的參數(shù)
List接口中的兩個(gè)overloadings的remove方法:
remove(E) 和 remove(int)。
由于generics 和 autoboxing 的加入,這兩個(gè)方法很容易使人迷惑
  • 相對(duì)于overloading方法,你總可以命名不同的方法名字,可以參考ObjectOutputStream中的write和ObjectInputStream中的read方法
  • 構(gòu)造函數(shù)只能被overloaded,不能被overridden
  • overload方法時(shí),不要在相同的參數(shù)位置上使用不同的functional interfaces,不同的functional interfaces 在根本上有可能是相同的
在使用可變長(zhǎng)度參數(shù)方法(varargs methods)時(shí),要謹(jǐn)慎
  • varargs 是指接受零個(gè)或多個(gè)具體類型的參數(shù)
  • varargs 的原理是:首先創(chuàng)建一個(gè)size等于傳入?yún)?shù)的個(gè)數(shù)的數(shù)組,然后把傳入?yún)?shù)的value放入該數(shù)組,最后把該數(shù)組傳入該方法
  • 從varargs的原理可知,在要求高性能的情景下,應(yīng)該少用varargs
一個(gè)方法應(yīng)該返回 empty collections or arrays, 而不是 nulls
  • 下面的幾個(gè)小例子
//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]);
}
  • 為了避免空collections或arrays的重復(fù)創(chuàng)建,可以使用Collections.emptyList,Collections.emptySet,Collections.emptyMap等進(jìn)行優(yōu)化
// 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);
}
一個(gè)方法返回optionals時(shí),要謹(jǐn)慎
  • 容器類型,包括 collections, maps, streams, arrays, and optionals,不應(yīng)該包裹在optionals里
  • Optional應(yīng)該僅僅用在:you should declare a method to return Optional<T> if it might not be able to return a result and clients will have to perform special processing if no result is returned
  • 你不應(yīng)該返回包裝原始類型(int, long, double)的Optional,應(yīng)該使用相應(yīng)的 OptionalInt, OptionalLong, OptionalDouble
  • 你不應(yīng)該用optional作為map的key, value, 以及 collection和array中的元素
  • 由于optional本質(zhì)上是object的分配和創(chuàng)建,讀取optional的value也有性能損失,因?yàn)樵谝蟾咝阅艿牡胤?,不適合使用optional
如果一個(gè)方法不能返回一個(gè)value,有哪些處理方法?
  • throw an exception
  • return null
  • return Optional<T>
對(duì)于所有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);
  • documentation comments 是 document your API 的最好最有效的方式
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • Spring Cloud為開(kāi)發(fā)人員提供了快速構(gòu)建分布式系統(tǒng)中一些常見(jiàn)模式的工具(例如配置管理,服務(wù)發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,663評(píng)論 19 139
  • 1. Java基礎(chǔ)部分 基礎(chǔ)部分的順序:基本語(yǔ)法,類相關(guān)的語(yǔ)法,內(nèi)部類的語(yǔ)法,繼承相關(guān)的語(yǔ)法,異常的語(yǔ)法,線程的語(yǔ)...
    子非魚(yú)_t_閱讀 34,775評(píng)論 18 399
  • 對(duì)象的創(chuàng)建與銷毀 Item 1: 使用static工廠方法,而不是構(gòu)造函數(shù)創(chuàng)建對(duì)象:僅僅是創(chuàng)建對(duì)象的方法,并非Fa...
    孫小磊閱讀 2,186評(píng)論 0 3
  • 《Effective Java》筆記(下) Enums and Annotations Item 30: Use ...
    OCNYang閱讀 2,101評(píng)論 1 5
  • 一直以來(lái),都覺(jué)得自己是一個(gè)多愁善感的人;淚點(diǎn)特別低,常常會(huì)因?yàn)橐粋€(gè)小小的感動(dòng)而淚光泛濫。參加婚禮會(huì)感動(dòng),看到新生兒...
    鈴鐺子90閱讀 277評(píng)論 1 3

友情鏈接更多精彩內(nèi)容