7 Best Practices for Java API Documentation
Photo by Emile Perron on Unsplash

7 Best Practices for Java API Documentation

The?Javadoc Tool?simplifies the documentation process in Java, allowing developers to document their code seamlessly as they write it. This article delves into 7 best practices for generating API documentation from Java source files using?Javadoc.


1. Follow the Comment Specification for Your Java Version

The tool uses a JavaDoc?doclet?to analyze the internal structure of the source files and produce corresponding output files.?The standard?doclet?generates HTML output, but it is possible to produce different outputs using different?doclets.

The comments recognized by the standard?doclet?are defined in the?Comment Specification?for Java 17. Note that the specification may vary between different Java versions.

2. Add Class-Level Comments With @author and @since

It’s always nice to include authors and contributors when creating a class, using the?@author?tag.

In some cases, like when you create artifacts like libraries, it is good practice to include the version in which the class was introduced with the?@since?tag.

/**
 * Methods for manipulating strings.
 *
 * @author David Buster
 * @author Annie Lonny
 * @author Jessamine Gerónimo
 * @since 1.0
 */
public class StringUtils { ... }        

The code above generates the following HTML documentation:

No alt text provided for this image

3. Add Method-Level Comments Including Inputs (@param) and Outputs (@return and @throws)

Make sure to include the parameters required by the method using the?@param?tag.

Include the possible outcomes, a returned value or an exception, using the?@return?and?@throws?tags.

/**
 * Returns a formatted decimal using the specified decimal pattern and argument.
 *
 * @param pattern  The pattern for the string format.
 * @param argument The object to format.
 * @return The formatted decimal.
 * @throws java.lang.IllegalArgumentException If the pattern is incompatible with the given argument.
 * @since 1.1
 */
public static String formatDecimal(String pattern, Object argument)
    throws IllegalArgumentException { ... }        

The code above generates the following HTML documentation:

No alt text provided for this image

4.?Reference Related Classes and Methods With?@see and {@link}

Add inline links using the?{@link}?tag and references using?@see?for the specified module, package, class, or member of a referenced class.

Both tags accept the same syntax for?module/package.class#member label.

/**
 * Returns the total with the currency symbol and the formatted decimal amount.
 *
 * @param currency {@link Currency} in which the amount is expressed.
 * @param amount   the total amount in {@link BigDecimal}.
 * @return The total using currency symbol and decimal format, e.g. $100,000.00.
 * @see #formatDecimal(String, Object)
 * @since 1.2
 */
public static String formatTotal(Currency currency, BigDecimal amount) { ... }        

The code above generates the following HTML documentation:

No alt text provided for this image

5. Use HTML

Use?HTML 5?tags in comments to generate more comprehensive documentation.

/**
 * Returns the formatted phone number based on the following patterns:
 * <ul>
 * <li>Pattern for 10-digit numbers: <em>(XXX) XXX-XXXX</em></li>
 * <li>Pattern for 7-digit numbers: <em>XXX-XXXX</em></li>
 * </ul>
 * <p><b>Note: The method will remove any non-digit characters from the input string.</b>
 *
 * @param phoneNumber the string phone number.
 * @return the formatted phone number.
 * @since 1.3
 */
public static String formatPhoneNumber(String phoneNumber) { ... }        

The code above generates the following HTML documentation:

No alt text provided for this image

6.?Format Code Snippets With?{@code} and <pre></pre>

Add inline code snippets using the?{@code}?tag,?this displays the text in code font without interpreting it as HTML or nested Javadoc tags.

The?<pre></pre>?tag is used to represent pre-formatted text in HTML. The key difference between this tag and?{@code}?is that it supports line breaks and indentation.

/**
 * Returns a masked credit card number whose last 4 characters are shown while the rest is masked using the
 * {@code maskCharacter} parameter of type {@link Character}.
 * <br>
 * <pre>
 * StringUtils.maskCreditCardNumber("4111111111111111") = "XXXXXXXXXXXX1111"
 * </pre>
 *
 * @param creditCardNumber the credit card number to be masked.
 * @param maskCharacter    this {@code Character} masks the digits of the card.
 * @return the masked credit card number.
 * @since 1.4
 */
public static String maskCreditCardNumber(String creditCardNumber, Character maskCharacter) { ... }        

The code above generates the following HTML documentation:

No alt text provided for this image

7. Generate Documentation and See the Results for Yourself

The?maven-javadoc-plugin?plugin simplifies the process of generating?Javadocs?for the specified project.

Add the plugin to your?pom.xml?file.

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-javadoc-plugin</artifactId>
            <version>3.3.1</version>
            <configuration>
                <source>17</source>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>
    </plugins>
</build>        

Run the command below to generate?Javadocs?in the?target/site?directory.

mvn javadoc:javadoc        

You can see the results by opening the generated?target/site/apidocs/index.html?file in your browser!


Thanks for reading. I hope this was helpful!

The example code is available on?GitHub.

要查看或添加评论,请登录

Jonathan Manera的更多文章

  • Service Discovery Patterns with Netflix Eureka

    Service Discovery Patterns with Netflix Eureka

    Modern distributed systems assign network locations dynamically, so you don’t know what IP address or port each service…

  • Spring Cloud Circuit Breaker Resilience4j

    Spring Cloud Circuit Breaker Resilience4j

    A distributed system, which comprises many services interacting to achieve business goals, is prone to failures in the…

  • Building Microservices with Spring Boot and?gRPC

    Building Microservices with Spring Boot and?gRPC

    gRPC Remote Procedure Call is a binary message based protocol for writing cross-language applications. As part of this…

  • Aspect Oriented Programming for?Babies

    Aspect Oriented Programming for?Babies

    Aspect Oriented Programming is a powerful tool that enables a clean modularization of “crosscutting” concerns of…

  • The Holy Trinity: JUnit5, Mockito, and Instancio

    The Holy Trinity: JUnit5, Mockito, and Instancio

    Unit testing is a software testing technique where individual components of an application (units) are tested in…

  • Code Quality Analysis with Sonar

    Code Quality Analysis with Sonar

    SonarQube is an open-source platform for continuous code quality inspection. This tool provides a detailed analysis of…

  • Mapping Bidirectional Object Associations using MapStruct

    Mapping Bidirectional Object Associations using MapStruct

    In object-oriented programming, an association is a relationship between two entities that defines how two objects…

  • API-First Design with OpenAPI Generator

    API-First Design with OpenAPI Generator

    APIs are contracts between services and their clients. These contracts are usually documented using an interface…

    1 条评论
  • Testing Microservices with Testcontainers

    Testing Microservices with Testcontainers

    When writing integration tests for Spring Boot applications, we usually need to access external resources such as…

  • 10 Meditations for Creative Professionals

    10 Meditations for Creative Professionals

    Sometimes, in our day-to-day life, we feel that something is not quite right. We find it hard to be as productive as we…

社区洞察

其他会员也浏览了