簡體   English   中英

在現有方法中添加新異常,而不會影響遺留代碼

[英]Add new exception in existing method without affecting legacy code

我在接受采訪時被問到這個問題。

我有一個方法說public int add(int i, int j) ,這個方法已被許多客戶端使用。

現在我必須對add方法進行更新(可能是一些增強),這會創建一個我必須拋出異常的場景。 如何讓現有客戶端繼續使用add()方法而無需更改代碼? [訪問者提示:客戶可能會也可能不會使用我在添加方法中所做的任何新增強]

首先,我想過重載add,換行添加一個新的add方法,拋出異常。 然后我RuntimException Exception作為RuntimException從添加...

但他們都沒有接受為正確的方法。

我缺少任何模式或設計方法?

方法1:使用Wrapper Class Integer

public class B {
    public int add(int i, int j) {
        return 0;
    }

    public int add(Integer i, Integer j) throws Exception {
        return 0;
    }
}

方法2:使用Overriding

你可以利用overriding method can choose not to throw exception at all

你可以做的是定義一個Parent類,這將有方法exceptionchilddoes 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM