2013-03-15 43 views
1

我經常發現自己在那裏我有一個這樣的方法簽名情況:在Java中重載方法時,您在哪裏計算附加參數數據?

public returnType doStuff(mandatoryParam, calculableParam1, calculableParam2); 

在這種情況下,我有時候想支持這些不同的方法簽名:

public returnType doStuff(mandatoryParam); 
public returnType doStuff(mandatory, calculable1); 
public returnType doStuff(mandatory, calculable2); 
public returnType doStuff(mandator, calculable1, calculable2); 

在做超載這樣的,是否更好地讓超載傳遞給基本方法是這樣的:

public returnType doStuff(mandatoryParam){ 
    doStuff(mandotryParam, null, null) 
} 

public returnType doSTuff(mandatoryParam, calculable1, calculable2){ 
    if(null == calculable1){ 
     calculable1 = calculate(); 
    } 
    . 
    . 
    . 
} 

或者是計算更好嗎? e可計算參數,然後將它們傳遞給像這樣的基本方法:

public returnType doStuff(mandatoryParam){ 
    Calculable calc1 = figureItOut1(); 
    Calculable calc2 = figureItOut2(); 
    doStuff(mandotryParam, calc1, calc2); 
} 
+2

這取決於。你是否想要更長的重載支持空引用,默認方式與其他引用相同? – 2013-03-15 22:04:34

+0

此外,你絕對的意思是超載,而不是按照你的頭銜重寫。 – 2013-03-15 22:06:23

+0

確實。我絕對意味着超載。錯字 – David 2013-03-15 22:10:54

回答

2

我會選擇第二種方法。第一種方法提供了更多的方法來做同樣的事情,這是API中冗餘的一個指示。

在某些情況下,有太多的參數應該有默認值,提供所有重載版本是不切實際的,而且對用戶來說也不會有什麼好處。然後應該只有一個基本方法接受空參數作爲參數的默認值。