簡體   English   中英

重載方法的 Javadoc 重用

[英]Javadoc reuse for overloaded methods

我正在開發一個 API,其中包含許多相同命名的方法,只是簽名不同,我猜這很常見。 它們都做同樣的事情,只是如果用戶不想指定,它們會默認初始化各種值。 作為一個易於理解的例子,考慮

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 的一些擴展? 或者我錯過了為什么不支持這個的充分理由?

我不知道有任何支持,但是,我會完全 javadoc 具有最多參數的方法,然后像這樣在其他 javadoc 中引用它。 我認為它足夠清楚,並且避免了冗余。

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

我只會記錄您的“最完整”方法(在本例中為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 );

可能沒有好的標准方法,因為即使是 JDK9 源代碼也只是簡單地復制粘貼大量文檔,例如,在:

4 行注釋重復。 哎呀,非干燥。

如果可以的話,把文檔放到界面上。 實現該接口的類將繼承 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));

您可能想在此處查看此 copy-mutator 模式:

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

根據參數組合的數量,這可能是更簡單、更簡潔的方法,因為 Params-Class 可以捕獲默認值並為每個參數提供一個 javadoc。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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