2011-09-28 52 views
0

我有2個替代方案來實現一個計算方法,我想知道什麼是更好的方法。Java方法過載

該方法需要一些int和double參數和(在某些情況下)一個特殊的標誌來做一些不同的計算。

在第一個示例中,我可以使用'calculateFoo(1,2.0d)'調用具有布爾標誌== FALSE的方法。

在第二個例子中,我總是要設置布爾標誌(即使我並不需要它)

方法1:(這裏我使用「...」作爲「方法的重載'參數)

public SomeObject calculateFoo(int pIntValue, double pDoubleValue, boolean... pDoSpecialStuff) { 

    if (pDoSpecialStuff.length == 0 || pDoSpecialStuff[0] == false) { 
     // method was called without boolean flag or boolean flag was set to FALSE 

     // do some calculation stuff 
     // ... 
    } else { 
     // method was called with boolean flag == TRUE 

     // do some other calculation stuff 
     // ... 
    } 

    return SomeObject; 
} 

方法2:(這是 '共同' 的做法)

public SomeObject calculateFoo(int pIntValue, double pDoubleValue, boolean pDoSpecialStuff) { 

    if (pDoSpecialStuff == false) { 
     // method was called with boolean flag == FALSE 

     // do some calculation stuff 
     // ... 
    } else { 
     // method was called with boolean flag == TRUE 

     // do some other calculation stuff 
     // ... 
    } 

    return SomeObject; 
} 
+8

而不是使用標誌來確定「做什麼」,你也可以有多種方法 - 一個方法 - 一個動作。這是面向對象的方法。旗幟通常很醜。 –

回答

1

考慮以下模式:

public ResultType calcFoo(int i, double d) { 
    return calc(i, d, false); 
} 

public ResultType calcFoo(int i, double d, boolean flag) { 
    if(flag) { 
     ... 
     return result; 
    } 
    else { 
     ... 
     return result; 
    } 
} 

一般來說,最好使用枚舉,而不是一個布爾標誌。它使您的代碼更具可讀性,並且速度更快。

我注意到你考慮使用可變參數。如果您想使用更多標誌,請考慮使用EnumSet將一組標誌傳遞給方法。如果你想傳遞0或1的標誌,可變參數更加肯定是一個反模式。

1

做第二個變種,因爲它是更加明確。可變參數將允許您傳遞多個布爾值,然後不使用它們。更好的是使用單個布爾值顯式地定義接口。

如果你想爲布爾標誌默認使用另一個重載:

public SomeObject calculateFoo(int pIntValue, double pDoubleValue) { 
    return calculateFoo(pIntValue, pDoubleValue, false); 
} 
0

我會定義另一個方法只有兩個參數來執行默認計算。

public SomeObject calcFoo(int, double) { 
    .... 
} 

public SomeObject calcFoo(int i, double d, boolean b) { 
    if(b) { 
     .... 
    } else { 
     return calcFoo(i, d); 
    } 
} 
2

兩個你的方法有碼味,布爾標誌吸

這裏是我的建議

public SomeObject calculateFoo(int pIntValue, double pDoubleValue) { 
    // normal calculation here 
} 

public SomeObject calculateFooSpecial(int pIntValue, double pDoubleValue) { 
    // special calculation here 
} 
+0

+1,並且這兩種方法都可以調用第三種私有方法,其中包含兩種計算共有的代碼 – michael667