2010-04-01 85 views
57

我正在開發一個API,其中有許多相同名稱的方法,只是簽名不同,我猜這是相當普遍的。他們都做同樣的事情,除非他們默認情況下初始化各種值,如果用戶不想指定。作爲可消化的例子,考慮Javadoc重用和重載的方法

public interface Forest 
{ 
    public Tree addTree(); 

    public Tree addTree(int amountOfLeaves); 

    public Tree addTree(int amountOfLeaves, Fruit fruitType); 

    public Tree addTree(int amountOfLeaves, int height); 

    public Tree addTree(int amountOfLeaves, Fruit fruitType, int height); 
} 

所有這些方法執行的基本動作是相同的;一棵樹種在森林裏。 API的用戶需要了解的有關添加樹的許多重要內容適用於所有這些方法。

理想情況下,我想編寫所使用的所有方法的一個的Javadoc塊:

/** 
    * Plants a new tree in the forest. Please note that it may take 
    * up to 30 years for the tree to be fully grown. 
    * 
    * @param amountOfLeaves desired amount of leaves. Actual amount of 
    * leaves at maturity may differ by up to 10%. 
    * @param fruitType the desired type of fruit to be grown. No warranties 
    * are given with respect to flavour. 
    * @param height desired hight in centimeters. Actual hight may differ by 
    * up to 15%. 
    */ 

在我的想象中,一個工具可能奇蹟般地選擇其中@params的應用到各種方法,和從而爲所有方法一次生成好的文檔。

使用Javadoc,如果我理解正確,我所能做的就是複製&粘貼相同的javadoc塊五次,每種方法的參數列表略有不同。這聽起來很麻煩,也很難維護。

有沒有辦法解決這個問題?對javadoc有一些擴展,有這種支持?還是有一個很好的理由,爲什麼我錯過了這個支持?

+0

偉大的問題和優秀的描述,謝謝。 – 2014-01-11 06:05:40

回答

50

我不知道有任何支持,但是,我會完全javadoc參數最多的方法,然後在其他javadoc中像這樣引用它。我認爲這足夠清晰,並避免冗餘。

/** 
* {@code fruitType} defaults to {@link FruitType#Banana}. 
* 
* @see Forest#addTree(int, Fruit, int) 
*/ 
+0

奇怪的是,當我從另一個文件中引用方法時,這種方法有效,但不是在同一個文件中(在Mac上的Eclipse 4.7中) - 當你試圖放棄一個過載並將調用者指向non-不贊成使用的過載。 – 2017-11-03 19:39:24

8

我只想記錄您的「最大」的方法(在這種情況下addTree(int,Fruit,int)),然後在JavaDoc其他方法請參閱本之一,並解釋如何/這是用於未提供的參數默認值。

/** 
* Works just like {@link ThisClass#myPow(double,double)} except the exponent is always 
* presumed to be 2. 
* 
* @see ThisClass#myPow(double,double) 
*/ 
static double myPow(double base); 
0

將文檔放入界面(如果可以的話)。 實現接口的類將繼承javadoc。

interface X(){ 
/** does fooish things */ 
void foo(); 
} 

class Ax implements X{ //automatically inherits the Javadoc of "X" 
@Override 
public void foo(){/*...*/} 
} 

如果你要繼承的文件,並添加你自己的東西給它,你可以使用{} @inheritDoc:

class Bx implements X{ 
/** 
    * {@inheritDoc} 
    * May fail with a RuntimeException, if the machine is too foo to be true. 
    */ 
@Override 
public void foo(){/*...*/} 
} 

參見: http://docs.oracle.com/javase/1.5.0/docs/tooldocs/windows/javadoc.html#inheritingcomments

現在我理解,這不完全是你想要的(你想避免同一類/接口中的方法重複)。爲此,您可以使用@see或@link,如其他人所述,或者您可以考慮您的設計。也許你想避免超載的方法,並使用一個單一的方法與參數對象,而不是像這樣:

public Tree addTree(TreeParams p); 

要這樣使用:

forest.addTree(new TreeParams().with(Fruits.APPLE).withLeaves(1500).withHeight(5)); 

你可能想有一個看看這個拷貝賦值函數圖形的位置:

https://brixomatic.wordpress.com/2010/03/10/dealing-with-immutability-and-long-constructors-in-a-fluent-way/

根據這可能是更容易和更清潔的方式,參數組合的量,因爲Params-Class可以捕獲默認值併爲每個參數設置一個javadoc。