Thursday, October 18, 2012

My Vocabulary Enum Pattern

When writing a library to be used by other developers, adding code documentation (javadoc) is essential.

Unfortunately javadoc often requires text duplication - which violates the don't repeat yourself (dry) principle.

This causes

  • incomplete documentation
  • outdated documentation
  • wasted time
In open source software I find this problem all the time.

One case where this becomes eminent is the following: a library that provides a builder for a simple value object. Where do you document the values? 
  1. In the setter of the builder? 
  2. In the Constructor of the value object? 
  3. In the private field of the value object?
  4. In the getter of the value object?
My solution to this is an enum called Vocabulary that contains all such values.

/**
 * Dictionary for terms used.
 *
 * <p>Javadoc can link to these values with details explanations, instead of copy/pasting 
 * the same limited and possibly outdated text.</p>
 */
public enum Vocabulary {

    /*
    Even though Java enums follow the convention to have all values in UPPER CASE,
    there is no need to follow this pattern here. Use the terms in the case that
    they appear in code.
     */

    /**
     * The api-key also known as user-id. 
     * A UUID of 44 characters such as "da39a3ee-5e6b4b0d-3255bfef-95601890-afd80709"
     */
    apiKey,

    /**
     * Such as "/service/ping". Starts with but doesn't end in a slash.
     */
    servicePath,

}

Then the builder and value object look like:

class MyValueObject {
    /**
     * @see Vocabulary #apiKey
     */
    public String getApiKey() { return apiKey; }
}

Within the IDE it's quick to get the explanation (ctrl-q in IntelliJ). And in the generated javadoc html pages it's just a click away. It would be nicer if there was a template syntax/conversion to inline the comment (is there?). Another thing I like about this is that it's easy on my eye - there is little noise in the javadoc. Once I understand the concept behind a term, I don't have to read it again.

Note: I do not add objects to the Vocabulary that are of a specific custom type. A String or Integer needs to be in because it's too general, the data type has no information about permitted value ranges. A MyType however already has the javadoc in its own class and thus usually does not need further documentation when used as a method parameter or return type.

No comments:

Post a Comment