![](/img/trans.png)
[英]Which design pattern is recommended when implementations only differ in a single method?
[英]Is having two versions of the same method which only differ in their signature (method name and 'throws' attribute) considered bad design?
我想設計一個API,其中我有兩個版本的相同方法, extractLastElement()
:
第一個版本沒有throws屬性: Object extractLastElementSafe();
將在客戶'確切知道'集合中有元素時使用,例如他剛剛添加了一些元素,因此不需要try-catch樣板代碼。
第二個版本將拋出Checked Exception: Object extractLastElement() throws NoMoreElementsException
; 當客戶不確定集合中是否還有元素時,例如在循環內部,將由客戶端使用。
這被認為是糟糕的設計嗎? 有沒有其他方法來模仿這種行為?
public class SomeCollection {
private List<String> arr;
public SomeCollection(List<String> arr) {
this.arr = arr;
}
public String extractLastElementSafe() {
return arr.remove(arr.size() - 1);
}
public String extractLastElement() throws NoElementsLeftException {
try {
return arr.remove(arr.size() - 1);
} catch (IndexOutOfBoundsException e) {
throw new NoElementsLeftException(e); // throwing a checked exception
}
}
}
class NoElementsLeftException extends Exception {
public NoElementsLeftException(Throwable cause) {
super(cause);
}
}
讓用戶以不同的方式做同樣的事情總是有問題的。 強迫客戶擔心最后一個元素是否存在也是不優雅的。
但最后,這更像是一種風格的東西,你的方法可以被認為是好的。 盡管如此,您還是要讓客戶端調用“安全”方法並最終得到運行時異常。 所以最終實際上有兩種不同的錯誤情況。
絕對改變的一個微妙的事情:避免代碼重復! 執行try / catch拋出該異常的方法應該只是調用“安全”方法!
說完所有這些:我個人只提供一種拋出一些運行時異常的方法。 標准Java集合使用未經檢查的異常,您也應如此。
引用羅伯特·馬丁的話說:“已檢查和未經檢查的例外之間的戰爭結束了,並且未經檢查就贏了”。 他在十多年前就寫過這篇文章。
如果您為方法的每個版本都有明確定義的使用方案,那么兩者都有意義。 這種設計決策的一個例子可以在Queue類中找到,它在兩種模式下工作,例如,嘗試從空隊列中刪除一個元素:一個方法( poll
)返回null,另一個( remove
)拋出異常。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.