Javadoc Guidelines

All Javadocs for the Liferay core and plugins must conform to the following guidelines.

The first sections of this wiki page describe general guidelines for documenting the different elements in a Java class and general guidelines for applying the various Javadoc tags. The Examples section of the document provides references to specific scenarios involving various class elements and Javadoc tags. This last section is intended to provide a quick cross reference for the author to use while writing Javadocs.

Before writing Javadocs, please familiarize yourself with the official Javadoc style guide.

General Guidelines #

  • All Javadocs should conform to the 80 column limit, just as with code.
  • The first paragraph in a Javadoc comment should not be surrounded by paragraph tags.
  • Any additional paragraphs should be wrapped in <p> and </p> tags.
  • All HTML tags (except for <b>, <i>, <code> etc.) should be on a line by themselves.
    • For an example of using table tags, see com.liferay.portal.kernel.annotation.AnnotationLocatorTest. Note: When using table tags, you must insert a line return between <table> and the start of the content nested within. The same rule also applies before the ending </table> tag.
    • For an example of using list tags, both ordered and unordered, see the class comment example below.
  • Never leave blank lines at the beginning or end of the comment.
  • Leave one blank line between paragraphs, lists, and between the last paragraph in the description and the first Javadoc tag (@author for instance).
  • Unordered and ordered lists in comments should be represented using <ul> or <ol> respectively. The <ul> and </ul> or <ol> and </ol> tags should each be on a line of their own. List items should each be placed on their own line, and the <li> and </li> tags should be on their own line immediately before and after the item text. Unordered and ordered lists must not be nested within paragraph tags; as format-javadoc condenses paragraph text into 80 columns and will thus ruin any separate-line formatting intended for the list related tags. See the class comment example below for proper use of list and paragraph tags.
  • @see and @link should not include the full path unless the class is in another package. If the class is in another package, then the full path to the class (e.g.{@link com.liferay.portal.kernel.util.Constants}) should be specified.
  • Wrap all keywords, special constants (true, false, null), and file names (portal-ext.properties) in <code></code> tags.
  • With regards to class constants, be sure to reference their class either by including the full path of the constant (e.g.{@link com.liferay.portal.kernel.util.Constants#TYPE_ASSET}) or wrapping the constant(s) in <code></code> tags followed by a reference to the class with its full path. For example, <code>TYPE_ASSET</code> and <code>TYPE_CREATOR</code> defined in {@link com.liferay.portlet.social.model.SocialActivityCounterConstants}.
  • Use a single space between a period ending a sentence and the start of the next sentence.

Example (class comment):

/**
 * Represents an example class. If a basic description requires more than one
 * sentence, include it in the first paragraph.
 *
 * <p>
 * Example of a second paragraph. Note the blank line between the first <p> tag
 * and the end of the first paragraph.
 * </p>
 * 
 * <ul>
 * <li>
 * Example list, item 1
 * </li>
 * <li>
 * Item two
 * </li>
 * </ul>
 * 
 * <p>
 * Another paragraph with more information in it. Example code should be placed
 * inside <pre><code> tags, as shown below.
 * </p>
 * 
 * <pre>
 * <code>
 * Example myExample = new Example();
 * </code>
 * </pre>
 * 
 * <p>
 * Notice the Javadoc tag values are lined up.
 * </p>
 * 
 * @author Brian Wing Shun Chan
 * @see	   BigExample
 */
public class Example {
	...
}

}}}

Javadoc Formatter #

Before committing any new or modified Javadocs, run ant format-javadoc on your code first! This will automatically wrap your comments to the proper width, format html tags, and line up Javadoc tags. The formatter will also propagate your Javadoc changes to the JSON interface for the class.

1. Compile the code

ant compile compile-test

2. Run the formatter

There are several options for invoking the basic formatting and Javadoc update functionality:

Basic formatting - Option 1 Run the formatter on one class at a time.

ant format-javadoc -Dlimit=SomeClassName

Basic formatting - Option 2 Run the formatter on all classes (this takes a bit longer).

ant format-javadoc

Javadoc update - Option 3 Have the formatter insert place holders for comment elements that are not up to date with the current method signatures.

ant format-javadoc -Dupdate=true [-Dlimit=SomeClassName]

For example, the formatter will add comment placeholders for parameters that are in method signatures but not present in the Javadoc comments for those methods.

3. Run the formatter as the final step After making all of your manual changes to Javadoc comments, you should format those changes.

ant format-javadoc [-Dlimit=SomeClassName]

Commit Process #

On pull requests containing Javadoc changes, be sure to notify Jim Hinkey

@jhinkey
in your comment so that your Javadoc changes will be reviewed.

Class Comments #

The following information should be present in the following order in the in the class comment:

  • Initial class description (paragraph/sentence)
    • First sentence - Should describe the class clearly and concisely. (required)
    • Followup sentences - Support the first sentence with important points about the class. Note, these sentences show up in the description for the class but do not show up in the summary table for the class. (optional)
  • Detailed class description (additional paragraph(s))
    • Provide more information on the class's purpose, abilities, and general role. For some classes (simple utility classes for instance) this additional information is not necessary if the initial paragraph provides an adequate description.
    • Usage examples or @link tags to where the class can be seen in use.
  • @author tags for each author of the class, from first to most recent. (required)
  • @see tags to other closely related classes whose Javadocs gives the reader a clearer picture of the purpose of this class.
  • @since tags. (as applicable)
  • @deprecated tags. (as applicable)

Class Descriptions #

Here are some rules of thumb for initial class descriptions:

  • Start with a verb - Whenever possible, start an initial class description with verb to describe the purpose of the class.

Example ( Localization interface):

Stores and retrieves localized strings from XML, and provides utility methods for updating localizations from JSON, portlet requests, and maps.

  • For service implementations (ServiceImpls)

Use these patterns:

Class Type Initial Description Pattern
LocalServiceImplProvides the local service for<summary of methods using actions ending in “ing”><entities (plural)>.
ServiceImplProvides the remote service for<summary of methods using actions ending in “ing”><entities (plural)>.

Example from DLAppLocalServiceImpl:

/**
 * Provides the local service for accessing, adding, deleting, moving,
 * subscription handling of, trash handling of, and updating document library
 * file entries, file ranks, and folders. All portlets should interact with the
 * document library through this class or through DLAppService, rather than
 * through the individual document library service classes.
 *
 * ...

In the above example:

  • the method summary states the service is for "accessing, adding, ... and updating" its entities.
  • the entities acted on are document library file entries, file ranks, and folders.

The method summary consists of a list of "ing" verbs in alphabetical order. You can derive these verbs from your method names. Note, you can use "accessing" to cover all the getters, fetchers, and search methods. And "updating" is typically adequate for covering the setters. But feel free to use the verbs that match your methods best.

  • For a model interface and its class - If some explanation is necessary to distinguish an interface from its class, follow the format below (taken from UserModel.java):
Provides the base model interface for the User service. Represents a row in the
&quot;User_&quot; database table, with each column mapped to a property of this
class.

Likewise, the description of the implementation could be as follows (from UserModelImpl.java):

Provides the base model implementation for the User service. Represents a row in the
&quot;User_&quot; database table, with each column mapped to a property of this
class.
  • Never begin with "This class" - Never begin the description with "This class" or anything similar. However, it is acceptable to use this wording in later sentences/paragraphs.

Class Javadoc Tags #

@author tags #

Use @author tags for each author of the class, from first to most recent.

@see tags #

Use @see tags to other closely related classes whose Javadocs would give the reader a clearer picture of the purpose of the class. This often includes the parent class, any important ancestors, and the primary classes that use this class.

@since tags #

The @since tag should always be used in cases where the class is a class that replaces an another class or where the class has been moved to a new package. Deprecations due to moving a class or replacing a class necessitate respective use of a @deprecated tag in the old class and a @since tag in the new class. For specifying the version, see Liferay's Versioning Schema section of Using Liferay Portal chapter 14.

The @since tag can optionally be used when the class is newly introduced.

The preferred format for common @since messages are listed below.

Reason@since Description
Replaced and former class@since version, replaced {@link fully qualified class}
Moved to different package@since version, moved from {@link fully qualified class}
New class@since version

For a working example, see StagedModelDataHandlerRegistry.

@deprecated tags #

The @deprecated tag should provide a short description that includes the release/version of initial deprecation, why the class was deprecated, and a link to what should be used in its place. For specifying the version, see Liferay's Versioning Schema section of Using Liferay Portal chapter 14.

Note, if a class deprecation was due to moving or replacing a class, then the comments for the new class should include an @since tag referencing the old class. See the former section for details.

The preferred format for common @deprecated messages are listed below.

Deprecation Reason@deprecated Description
ReplacedAs of version, replaced by {@link fully qualified class}
Moved to different packageAs of version, moved to {@link fully qualified class}
Some other reasonAs of version, due to some reason

Method Comments #

The following information should be present in the Javadoc comment on each method:

  • A short, one sentence description of the method.
  • Additional sentences and/or paragraphs providing more information on the method's purpose and function. Any information the user of the method would find useful should be included here, including special requirements, circumstances where it should/should not be used, etc. For many methods, this additional explanation is not necessary, particularly for getters and setters.
  • Usage examples if necessary and possible. Trivial methods don't need examples, and if an example would be extremely large, simply @link to a place the method is used.
  • If the method is only used in one or two places, @link to the methods it is called from. This helps later developers to understand its role in Liferay.
  • No need to mention matching a company ID parameter. It should be understood and is not worth cluttering the description.

The following information should always be present in the following order in the Javadoc tags for the method:

  • The method parameters, in order, with descriptions.
  • All possible return values, including null. If the method is void, do not include this.
  • The exceptions the method can throw, in order, with explanations of what would trigger them.

Example:

/**
 * Returns the localized preferences values for the key, optionally using the
 * default language if the no localization exists for the requested
 * language.
 *
 * @param  preferences the preferences container
 * @param  key the preferences key
 * @param  languageId the id of the language
 * @param  useDefault whether to use the default language if no localization
 *		   exists for the requested language
 * @return the localized preferences values. If <code>useDefault</code> is
 *		   <code>false</code> and no localization exists for the requested
 *		   language, an empty array will be returned.
 */
public String[] getPreferencesValues(
	PortletPreferences preferences, String key, String languageId,
	boolean useDefault);

Method comments for interfaces and sub-classes

  • Interface method Javadoc is always required.
  • Sub-class Method Javadoc is required for methods of sub-classes that have differences from their parent class(es) that should be noted. Some examples are sub-class methods that have different behavior, different side-effects, and/or different requirements of their parameters. Otherwise, the method Javadoc of the interface or super-class is applied to the sub-class automatically. For example, the method Javadoc of RawMetadataProcessor is applied to RawMetadataProcessorImpl.generateMetadata().

Method Descriptions #

Initial Method Descriptions #

Always use a verb to describe the method. The preferred format for the descriptions of several common methods are listed below.

Method Type Description
constructor(value) Constructs a new ... with the value.
setSomething(value) Sets thesomething of this thing.
getSomething() Returns thesomething of this thing.
getSomethings() Returns thesomethings of this thing. (Note, do not refer to collection type; instead, refer to the something in plural form.)
setSomething(boolean) Sets whetherthis thing is something.
isSomething() Returns <code>true</code> ifthis thing is something.
deleteSomething() Deletes thesomething.

There are two general rules for method descriptions:

  1. When referring to the current instance, say "this something". Example: "Returns <code>true</code> if this person is an administrator."
  2. When referring to parameters, use "the" instead of "a". Example: "Returns the localized preferences value for the key."

Try to avoid simply restating the name of the method in the description. In some cases, such as with getters/setters, this is fine, but if it is not immediately obvious what a method does, it needs more explanation.

For example, the following is NOT a good example of a method description:

/**
 * Updates the localization.
 */
public String updateLocalization(String xml, String key, String value, String requestedLanguageId);

Write the following instead:

/**
 * Updates the localized string for the language in the localizations XML.
 */
public String updateLocalization(String xml, String key, String value, String requestedLanguageId);

Detailed Method Descriptions #

If there is both a getter and setter for the same property/collection on the object, place the detailed description on the setter/add method. The getter method should have a one sentence description, and @see the method with more detail.

If there are multiple overloaded methods of the same name, each method should have a complete description of itself. Do not @see the other overloaded forms.

More on Method Descriptions #

Start the description with “Returns ...” for a method used primarily for the value it returns.

Getters should always follow this rule. Methods that involve returning a count or a search result should typically follow this rule as well.

/**
 * Returns the organization with the primary key.
 *
 * ...
 */
public Organization getOrganization(long organizationId)

Distinguish between overloaded methods

Distinguish between overloaded methods by uniquely describing each method in the first sentence of the method description. This helps developers spot out which of the overloaded methods they want to use when viewing the Javadoc summary of the methods for the class. Remember, only the first sentence of the method description shows in the method summary. The remaining sentences (including sentences of the same paragraph following the first sentence) are available in the full length method description.

/**
 * Returns all immediate subfolders of the parent folder.
 * ...
  */
public List<Folder> getFolders(long repositoryId, long parentFolderId)

and

/**
 * Returns all immediate subfolders of the parent folder, optionally
 * including mount folders for third-party repositories.
 * ....
 */
public List<Folder> getFolders(long repositoryId, long parentFolderId, boolean includeMountFolders)

Refer to parameters with "the", not "a" or "given"

By using "the" (e.g. "the parent folder") it is assumed the reader will understand we are refering to an entity related to a parameter (e.g. the folder associated with parameter parentFolderId).

/**
 * Returns all immediate subfolders of the parent folder.
 *
 * ...
 * @param  parentFolderId the primary key of the folder's parent folder
 * ...
 */

Multiple Sentences in Initial Method Description

Unless the details describing a method warrant a paragraph, simply add the sentence(s) directly after the initial method description.

/**
 * Returns the parent organizations in order by closest ancestor.  The list starts with the organization itself.
 *
 * ...
 */
public List<Organization> getParentOrganizations(long organizationId)

Important: In the HTML generated from the Javadoc, only the initial method description sentence will appear in the method summary table. But the sentences that follow the initial method description will show in the method details.

Method Javadoc Tags #

@param tags #

@param tags should provide a short description of what the parameter is or what it is for, as well as any special requirements. If more detail is needed than what can fit in one or two sentences, place it in the method description instead. Never start the parameter description with a capital letter, and always refer to the parameter with "the" rather than "a". Additionally, it is unnecessary to explain what the parameter is for if this was already explained in the method description.

The preferred format of several common parameter types are shown below. Be sure to include the description text found in bold.

Param case Param name convention @param Description
An entity's ID entityIdthe primary key of theentity
An entity's attribute or fieldtheentity'sattribute
An involved entity (possibly the method's subject) classname (lowercase) the(refer to the entity in layman's terms in lower case. Do not refer to the uppercase classname)
A boolean parameter whetherto do something or some condition is true

Bad example:

/**
 * Returns the name of the role.
 *
 * @param roleId the primary key of the role **whose name to get**
 * @return the name of the role
 */
String getRoleName(long roleId)

Good example:

/**
 * Returns the name of the role.
 *
 * @param roleId the primary key of the role
 * @return the name of the role
 */
String getRoleName(long roleId)

To show possession, use an apostrophe rather that ending a sentence with a preposition. The only exception is that when referring to a primary key, always write "the primary key of the user", not "the user's primary key". Example:

/**
 * @param  creatorUserId the primary key of the user's creator
 * @param  companyId the primary key of the user's company
 * @param  name the user's name
...
 * @param  groupIds the primary keys of the user's groups
 */
public User addUser(long creatorUserId, long companyId, name, ... , long[] groupIds, ...)

@return tag #

The @return tag should provide a short description of what the method returns, including any special values. If a method returns null, this should be explicitly stated. Otherwise, the reader should assume the method will always return its designated type.

As a rule of thumb, describe the return value in simple terms. Leave to method and parameter descriptions details on what can cause subtle variations in values returned.

The preferred format for the return descriptions of several common method types are shown below.

Method Type@return Description
getSomething()thesomething of this thing
getSomethings()thesomethingsof this thing (Note, do not refer to the collection type; instead, refer to the something in plural form)
changeSomething(thing)thechanged thing, or <code>null</code> if thechange failed
isSomething()<code>true</code> ifsomething; <code>false</code> otherwise

Note using the word "the" (not "a" or "an") in describing the returned item.

Abbreviating return description when extensive matching done

If a method uses more than two criteria items to match an entity or is awkward to consolidate into a small sentence, just use the phrase "the matching somethings" to start of the description of the returned entities.

/**
 * Returns an ordered range of all the file entries in the group starting at
 * the root folder that are stored within the Liferay repository.
 * ...
 * @return the range of matching file entries ordered by the comparator
 * ...
 */

Parameter Side Effects

Only include a message about the side effects of a parameter in the @return description if the parameter can have a side effect apart from the main purpose of the method. For instance, if the primary purpose of a parameter was to tell the method to use an alternate data source, but a failure in using the alternative data source caused the method to return null rather than throw an exception, say in the @param the parameter can change the data source, and then say in the @return that a failure in using the alternative data source could cause null to be returned, and say in the @throws the exception wouldn't be thrown under this circumstance.

@throws tags #

@throws should give a short description of when an exception will be thrown. They should always be written in the past tense.

It is often difficult to describe exactly what will cause certain exceptions to be thrown, particularly in the case of SystemException. For this exception, simply use the following generic description:

@throws SystemException if a system exception occurred

If you do know what could cause an exception, briefly describe the circumstances. For example:

@throws PortalException if a user with the primary key could not be found

If you describe what could cause an exception, but cannot provide an exhaustive list of all of the possible causes, simply end your comment generalizing that the type of exception could have occured. For example:

@throws PortalException if a user with the primary key could not be
        found, if the XSD was not well-formed, or if a portal a exception
        occurred

By definition, system exceptions are only thrown when something has gone wrong with the system, such as a database server going offline, a filesystem becoming corrupted, or any number of other impossible to predict things going wrong. This is the reason the completely generic "if a system exception is thrown" message is used for system exceptions. All the information that we can really give a developer about the reasons for a system exception being thrown is available in the documentation for SystemException, so there is no need to duplicate this information in essentially every method in Liferay.

Descriptions of portal exceptions should include situations that can be predicted and explained to some extent. For example, methods that take a primary key will generally throw a PortalException when a record with that primary key cannot be found. Other methods will throw a PortalExceptions on validation errors.

Key Not Found

Pattern: if a <entity1>[ or entity2] with the primary key could not be found

Invalid Information

Pattern: if the <entity's> information was invalid

Start New Reasons with 'if'

Start each new type of reason for the exception with the word if.

Pattern: @throws PortalException if <reason type1> or if <reason type2>

/**
 * ...
 * @throws PortalException if a creator or parent organization with the primary key could not be found or if the organization's information was invalid
 * ...
 */
public Organization addOrganization(long userId, long parentOrganizationId, … , ServiceContext serviceContext)
throws PortalException, ...

@see tags for methods #

Only use @see when there are more details about something that could be gained by reading the docs for another method or class.

@since tags for methods #

The @since tag should be used in cases where the method is a result of renaming a former method. It can optionally be used when the method is newly introduced to an existing class.

Note, deprecations due to renaming a method should include both the use of @deprecated in the old method and @since in the new method.

The preferred format for common @since messages are listed below.

Reason@since Description
Renamed a former method@since version, rename of {@link #someMethod()}
Generalization@since version, replaced {@link #someMethod()}
New method@since version

@deprecated tags for methods #

The @deprecated tag should provide a short description that includes the release/version of initial deprecation, why the method was deprecated, and a link to what should be used in its place. For specifying the version, see Liferay's Versioning Schema section of Using Liferay Portal chapter 14.

Note, if a method deprecation was due to moving or replacing a method, then the comments for new method should include an @since tag referencing the old method. See the previous section for details.

The preferred format for several common @deprecated messages are listed below.

Deprecation Reason@deprecated Description
ReplacedAs of version, replaced by {@link fully qualified path or #method name}
Renamed within same classAs of version, renamed to {@link #someMethod()}
Generalized in another method within same classAs of version, replaced by the more general {@link #someMethod()}
Moved to different packageAs of version, moved to {@link fully qualified path}
Some other reasonAs of version, due to some reason

For a working example, see LayoutSetLocalService.updateLayoutSetPrototypeLinkEnabled(...).

Examples #

This section provides examples of Javadocs for various types of situations. For each example, an explanation is given, a pattern is identified, and a reference to Javadoc in a Liferay class is given. Each example is listed in the Table of Contents for quick lookup.

Class: Initial and detailed description #

The Localization interface demonstrates our guidelines for initial and detailed class descriptions well.

Stores and retrieves localized strings from XML, and provides utility methods for updating localizations from JSON, portlet requests, and maps. Used for adding localization to strings, most often for model properties.

Localized values are cached in this class rather than in the value object since value objects get flushed from cache fairly quickly. Though lookups performed on a key based on an XML file are slower than lookups done at the value object level in general, the value object will get flushed at a rate which works against the performance gain. The cache is a soft hash map which prevents memory leaks within the system while enabling the cache to live longer than in a weak hash map. 

Note the following from this example:

  • The first sentence of the initial class description starts with a verb (two verbs, in fact).

Stores and retrieves ...

  • A followup sentence supports the initial class description's first sentence.

...  Used for adding localization to strings, most often for model properties.

  • The second paragraph provides a helpful description of the classes details.

Constructor: with parameters #

Constructor Description Pattern: Constructs a new <something> with ... <list each parameter in layman's terms>

/**
 * Constructs a DayAndPosition with the day of the week and day position.
 *
 * @param d day of the week
 * @param p day position
 */
public DayAndPosition(int d, int p) 

For a working example, see StringParser.StringParser(...)

Method: Get by primary key #

The primary key need not be mentioned in the method description, as the primary key is part of the method signature and should have a parameter description.

Method Description Pattern: Returns the <something> with the primary key

Return Tag Pattern: the something of this thing

/**
 * Returns the organization with the primary key.
 *
 * @param  organizationId the primary key of the organization
 * @return the organization
 */
public Organization getOrganization(long organizationId)

For a working example, see OrganizationService.getOrganization(...).

Method: Deletes/Removes something #

The primary key need not be mentioned in the method description, as the primary key is part of the method signature and should have a parameter description.

Method Description Pattern:

Deletes the <something> or Removes the <something>

Return Tag Pattern: the something that was removed

Method: Get/search/count matching a single field #

Methods that involve straight matching of fields to simple values should use the following pattern ...

Method Description Pattern: Returns <something> with the <field1>... .

Example:

/**
 * Returns the primary key of the user with the email address.
 *
 * ...
 * @return the user with the email address
 */
public long getUserIdByEmailAddress( ... , String emailAddress)

For a working example, see UserService.getUserByEmailAddress(...).

Method: Get/search/count matching multiple fields #

At times it you may have a whole set of parameters used to find/match an entity instance. To simplify things, describe your method as "matching" these parameters and list the parameters.

Method Description Pattern: Returns <something> matching the <field1> [,<field2>, ... <fieldN>] and <fieldN+1> …

Example:

/**
 * Returns all the structures matching the group, name, and description.
 * ...
 * @return the matching structures
 */
public List<DDMStructure> getStructure(long groupId, String name, String description)

For working examples, see DDMStructure.getStructure(long groupId, String name, String description)

Method: Get/search/count by field-to-keyword matching #

Methods for which individual fields are matched with corresponding keyword parameters, should follow the pattern ...

Method Description Pattern: Returns <somethings> whose <fieldA>[, <fieldB>, … or <fieldZ>] match the keywords specified for them …

Method: Get/search/count by Combined Field Value and Field-to-Keyword Matching #

Methods for which straight matching of fields to simple values is done, and for which individual fields are matched with corresponding keyword parameters, should follow the pattern ...

Method Description Pattern: Returns <somethings> with the <field1>[, <field2>, … and <fieldn>], and whose <fieldA>[, <fieldB>, … and <fieldZ>] match the keywords specified for them ...

/**
 * Returns an ordered range of all the users with the status, and whose
 * first name, middle name, last name, screen name, or email address match
 * the keywords specified for them, ...
 * ...
 * @return the matching users
 */
public List<User> search(long companyId, String firstName, String middleName, String lastName, String screenName, String emailAddress, int status, ... )

For a working example, see UserLocalService.search(...).

Method: Returning a boolean #

If a method returns a boolean, only the condition(s) for which the method returns true need be included in the initial method description.

Method Description Pattern: Returns <code>true</code> if <satisfying condition(s)>

Return Tag Pattern: <code>true</code> if something; <code>false</code> otherwise

/**
  * Returns <code>true</code> if the user is a member of the group.
  *
  * ...
  * @return if the user is a member of the group; <code>false</code> otherwise
  */
public boolean hasGroupUser(long groupId, long userId)

For a working example, see UserService.hasGroupUser(...).

Method: Returning a count #

If a method returns some sort of count, then use the following pattern...

Method Description Pattern: Returns the number of <something> ...

Hint, if a method name contains the word “Count” or the method returns an int, it may qualify for this pattern.

For a working example, see OrganizationLocalService.searchCount(...).

Method: Returning a collection #

Precede the reference to the entity instances with the term “all the”.

Method Description Pattern: Returns … all the <entities> …

Return Tag Pattern: the somethingsof this thing (Note, do not refer to the collection type; instead, refer to the something in plural form)

/**
 * Returns all the organizations associated with the user.
 *
 * ...
 * @return the organizations associated with the user
 */
public List<Organization> getUserOrganizations(long userId)

For a working example, see OrganizationService.getUserOrganizations(...).

Method: Returning an ordered range of values #

If the collection returned is ordered, mention that in the method description.

Method Description Pattern: Returns an ordered range of ...

Return Tag Pattern: the somethingsof this thing (Note, do not refer to the collection type; instead, refer to the something in plural form)

/**
 * Returns an ordered range of all the users with a social relation of the type with the user.
 *
 * ...
 * @return the ordered range of users with a social relation of the type with the user
 */
public List<User> getSocialUsers(long userId, int type, int start, int end, OrderByComparator obc)

For a working example, see UserLocalService.getSocialUsers(...).

Method: Returning an ordered values NOT as a range of values #

Sometimes, you'll need to describe your method that returns the entire collection of values, that are not a part of a paginated range, and are ordered.

Example:

/**
 * Returns all the structures matching the class name ID ordered by the 
 * comparator.
 * ...
 */
public List<DDMStructure> getClassStructures(long companyId, long classNameId, OrderByComparator orderByComparator)

See DDMStructure.getClassStructures().

Method: Returning a ranged collection #

If the collection returned is a subset of the total collection with a specified start and end index, refer to the subset as a range.

Method Description Pattern: Returns an ordered range of …

Return Tag Pattern: the somethingsof this thing (Note, do not refer to the collection type; instead, refer to the something in plural form)

/**
 * Returns an ordered range of all the users with a social relation of the type with the user.
 *
 * ...
 * @return the ordered range of users with a social relation of the type with the user
 */
public List<User> getSocialUsers(long userId, int type, int start, int end, OrderByComparator obc)

For a working example, see UserLocalService.getSocialUsers(...).

Method: Describing overloaded methods #

In most cases, you'll find the overloaded methods calling one of the others--we'll refer to this as the main method. Here are some rules of thumb ...

If there are only 2 overloaded methods...

...you can simply describe the main method as having additional parameters.

Method1 (main):

/**
 * Adds an organization with additional parameters.
 */
addOrganization(long parentOrganizationId, String name, String type, boolean recursable, long regionId, long countryId, int statusId, String comments, boolean site, List<Address> addresses, List<EmailAddress> emailAddresses, List<OrgLabor> orgLabors, List<Phone> phones, List<Website> websites, ServiceContext serviceContext)

Method2:

/**
 * Adds an organization.
 */
addOrganization(long parentOrganizationId, String name, String type, boolean recursable, long regionId, long countryId, int statusId, String comments, boolean site, ServiceContext serviceContext)

For a working example, see the addOrganization methods in OrganizationServiceImpl.

If there are 3 or more overloaded methods...

... focus on their distinguishing parameters.

Example, 3 overloaded methods named addStructure() and their distinguishing method descriptions.

Method1 (main):

/**
 * Adds a structure referencing its parent structure.
 */
addStructure(long userId, long groupId, long parentStructureId, long classNameId,
String structureKey, Map<Locale, String> nameMap, Map<Locale, String> descriptionMap, String xsd, String storageType, int type, ServiceContext serviceContext)

Method2:

/**
 * Adds a structure referencing a default parent structure, using the portal
 * property <code>dynamic.data.lists.storage.type</code> storage type and
 * default structure type.
 */
addStructure(long userId, long groupId, long classNameId, Map<Locale, String> nameMap, Map<Locale, String> descriptionMap, String xsd, ServiceContext serviceContext)

Method3:

/**
 * Adds a structure referencing a default parent structure if the parent
 * structure is not found.
 */
addStructure(long userId, long groupId, String parentStructureKey, long classNameId, String structureKey, Map<Locale, String> nameMap, Map<Locale, String> descriptionMap, String xsd, String storageType, int type, ServiceContext serviceContext)

Note, you can still consider appending with additional parameters at the end of the main method if it makes sense.

Method: Password Policy Methods #

The following represents different types of methods that involve relationship of an entities to password policies.

Password Policy - Add

Method Description Pattern: Assigns the password policy to the <entity(s)>, removing any other currently assigned password policies.

For a working example, see UserService.addPasswordPolicyUsers(...).

Password Policy - Has

Method Description Pattern: Returns <code>true</code> if the password policy has been assigned to the <entity>.

For a working example, see UserLocalServiceImpl.hasPasswordPolicyUser(...).

Password Policy - Unset

Method Description Pattern: Removes the <entity(s)> from the password policy.

For a working example, see UserService.unsetPasswordPolicyUsers(...).

Method: Uses a property #

If your parameter uses a property, be sure to mention the kind of property it is (e.g. portal property, portlet property, Liferay plugin package property, etc) and mention the property name explicitly wrapped in code tags.

Here is an example from DDMStructureLocalService:

/**
 * Adds a structure referencing a default parent structure, using the portal
 * property <code>dynamic.data.lists.storage.type</code> storage type and
 * default structure type.
 * ...
 */
addStructure(long userId, long groupId, long classNameId, Map<Locale, String> nameMap, Map<Locale, String> descriptionMap, String xsd, ServiceContext serviceContext)

Parameter: Primary key #

Refer to primary keys explicitly. Do not refer to them as IDs, even if the parameter uses Id in its name (e.g. organizationId).

/**
 * ...
 * @param  organizationId the primary key of the organization
 * ...
 */
public Organization getOrganization(long organizationId)

For a working example, see OrganizationService.getOrganization(...).

Parameter: Attribute/field #

When describing parameters that represent entity fields, use the possessive form of the entity to show ownership of the field. This is often applicable in describing parameters in add/update methods for an entity.

/**
 * ...
 * @param name the organization's name
 * @param type the organization's type
 * ...
 */
public Organization addOrganization(..., String name, String type, …)

For a working example, see OrganizationService.addOrganization(...).

Parameter: Boolean #

When describing boolean parameters, always start the description with the word whether. Two common uses of a boolean parameter are the following:

  • The parameter indicates some condition. Therefore, describe the condition in terms of it being true.
  • The parameter indicates whether to do something. Therefore, describe the action to be performed when the parameter value is true.

Example,

/**
 * ...
 * @param male whether the user is male
 * ...
 * @param sendEmail whether to send the user an email notification about their new account
 * ...
 */
public User addUser(
			..., boolean male,
			..., boolean sendEmail,
			...)

For a working example, see UserService.addUser(...).

Parameter: ClassNameId #

When describing the classNameId parameter, identify if the method is referring to its own service model or to a related model. Then, use the appropriate pattern below based on which class name is being used.

Uses own service model's class name ID - True

Parameter Description Pattern: the primary key of the <entity's> class name

Uses a related model's class name ID - True

Parameter Description Pattern: the primary key of the class name for the <entity's> related model

For a working example, see DDMStructureLocalServiceImpl.addstructure(...).

Parameter: Entity (primary) #

Use this pattern when an entity (typically of a class type) is either the subject of the method or involved in the method's behavior.

/**
 * ...
 * @param user the user
 * ...
 */
public boolean isPasswordExpired(User user)

For a working example, see UserLocalService.isPasswordExpired(...).

Parameter: ServiceContext #

For every method that accepts a ServiceContext param, the javadoc for that param should specify which fields within the ServiceContext are mandatory and which other fields are taken into account if specified.

Here are the rules to follow:

  1. Provide a simple description of the service context. If it can optionally be null, include that information in this first sentence.
  2. In the next sentence, start with “Must set” and describe any service context fields which are mandatory.
  3. In the next sentence, start with “Can set” or "Can merge" and describe any service context fields which, if specified, can be used by the underlying implementation.If there are a combination of fields that can be set and fields that can be merged, mention the fields that can be set before the fields that can be merged.
  4. Any service context attribute specifically named should be wrapped in <code></code> tags. Example, a service context's <code>fieldEntryTypeId</code>.

Parameter Tag Pattern:

@param serviceContext the service context to be applied [ (optionally <code>null</code>) ] . [ Must set the <field1> [, <field2>, … and <fieldN> ] for the <entity>. ] [ Can (set | merge) the <fieldA> [, <fieldB>, … and <fieldZ> ] for the <entity>. ]

/**
 * ...
 * @param  serviceContext the service context to be applied (optionally
 *         <code>null</code>). Can set asset category IDs and asset tag
 *         names for the organization, and merge expando bridge attributes
 *         for the organization.
 * ...
 */
public Organization updateOrganization( ... , ServiceContext serviceContext)

Note, in the above example there are no mandatory service context fields. However, the method does apply replacement field values and new field values.

Parameter: And/or operator #

The following is an example of how an and/or operator parameter may be described. Note, be sure to check the specific use of the operator in order to describe it properly.

/**
 * ...
 * @param  andSearch whether every field must match its keywords, or just
 *         one field. For example, &quot;users with the first name 'bob' and
 *         last name 'smith'&quot; vs &quot;users with the first name 'bob'
 *         or the last name 'smith'&quot;.
 * ...
 */
public List<User> search( ... , String firstName, String middleName, … , boolean andSearch, ... )

For a working example, see UserLocalService.search(...).

Parameter: Refer reader to more information #

To direct a reader to another class or URL containing more information related to the parameter, add a sentence with a link to that information.

Parameter Tag Pattern:

@param the parameter's description. For more information see {@link fully-qualified class name}.

Example,

 * @param  params the finder params. For more information see {@link
 *         com.liferay.portal.service.persistence.OrganizationFinder}

This example is used in comments for several of the search methods in OrganizationLocalService.

Return: Ordered collection #

For ordered collection returned, mention how or what determines the order

Examples,

@return the range of matching file entries ordered by the comparator

@return the range of matching file entries ordered by date modified

For working examples, see DDMStructure.getStructures(long groupId, long classNameId, int start, int end, OrderByComparator orderByComparator) and DLAppServiceImpl.getGroupFileEntries(...).

Return: Significantly varying values #

If a method can return values significantly different or special known values, separate the descriptions of these values using commas – even if there are only two such differing values. This convention helps to emphasize differences between them.

@return the primary key of the organization, or <code>0</code> if the organization was not found

Note, the convention of separating two values with a comma is only used with describing return values. This convention is not to be used with the other tags (e.g. @param, @throws).

For a working example, see OrganizationLocalService.getOrganizationId(...).

0 Attachments
24801 Views
Average (3 Votes)
The average rating is 5.0 stars out of 5.
Comments
Threaded Replies Author Date
Thank you for this guide! If only all Liferay's... Nicolas Forney July 20, 2011 12:36 AM

Thank you for this guide!
If only all Liferay's classes could follow those guidelines...
Posted on 7/20/11 12:36 AM.