[英]Add new exception in existing method without affecting legacy code
我在接受采訪時被問到這個問題。
我有一個方法說public int add(int i, int j)
,這個方法已被許多客戶端使用。
現在我必須對add方法進行更新(可能是一些增強),這會創建一個我必須拋出異常的場景。 如何讓現有客戶端繼續使用add()
方法而無需更改代碼? [訪問者提示:客戶可能會也可能不會使用我在添加方法中所做的任何新增強]
首先,我想過重載add,換行添加一個新的add方法,拋出異常。 然后我RuntimException
Exception作為RuntimException
從添加...
但他們都沒有接受為正確的方法。
我缺少任何模式或設計方法?
public class B {
public int add(int i, int j) {
return 0;
}
public int add(Integer i, Integer j) throws Exception {
return 0;
}
}
你可以利用overriding method can choose not to throw exception at all
。
你可以做的是定義一個Parent
類,這將有方法exception
和child
類does not have the exception
,並會從父覆蓋方法。 現在,當您希望客戶端使用帶有類型A
異常傳遞引用的add
時,否則傳遞帶有類型B
引用:
class A { // <---New Class
public int add(int i, int j) throws Exception { // <-- Method with Exception
return 0;
}
}
class B extends A { // <----Original Class
@Override
public int add(int i, int j) { // <--- Original Method
return 0;
}
}
如果客戶端不老,您可以添加新的add(int i,int j,boolean isOldClient)方法並拋出運行時異常。 (也許使用一些更好的名稱而不是isOldClient)。
然后做這樣的事情
// legacy method
public int add(int i, int j) {
return add(i, j, true);
}
// new add method
public int add(int i, int j, boolean isOldClient) {
...
if (!oldClient) {
... // add code that throw exception
throw new RuntimeException();
}
...
}
新客戶端可以使用帶有額外參數的新add方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.