A short summary of Java coding best practices
By: Rafiullah Hamedy
Tags: Documentation, Clean Code, Java, Coding Style, Coding Conventions

Documentation and Comments

It’s worth mentioning that almost all code goes changes throughout its lifetime and there will be times when you or someone is trying to figure out what a complex block of code, a method, or a class is intended to do unless clearly described. The reality is almost always as follow

There are times that the comment on a complex piece of code, method, class does not add any value or serve its purpose. This usually happens when commenting for the sake of it.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Let’s get started. There are two types of comments

Implementation Comments — are meant to comment out code or comment about a particular implementation of the code.

Documentation Comments — are meant to describe the specification of the code from an implementation-free perspective to be read by developers who might not necessarily have the source code at hand.

The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.

Types of Implementation Comments

There are four (4) types of implementation comments as shown below

Block comment — see example below

— see example below Single line comment — when the comment is not longer than a line

— when the comment is not longer than a line Trailing comments — Very short comment moved to the right end

— Very short comment moved to the right end End of line comment — begins a comment that continues to the newline. It can comment out a complete line or only a partial line. It shouldn’t be used on consecutive multiple lines for text comments; however, it can be used in consecutive multiple lines for commenting out sections of code.

// Block comment

/*

* Usage: Provides description of files, methods, data structures

* and algorithms. Can be used at the beginning of each file and

* before each method. Used for long comments that do not fit a

* single line. 1 Blank line to proceed after the block comment.

*/ // Single line comment

if (condition) {

/* Handle the condition. */

...

} // Trailing comment

if (a == 2) {

return TRUE; /* special case */

} else {

return isPrime(a); /* works only for odd a */

} // End of line comment

if (foo > 1) {

// Do a double-flip.

...

} else {

return false; // Explain why here.

} //if (bar > 1) {

//

// // Do a triple-flip.

// ...

//}

//else

// return false;

Documentation comments (i.e. Javadoc)

Javadoc is a tool that generates HTML documentation form your java code using the comments that begin with /** and end with */ — see Wikipedia for more details on how Javadoc works or just read along.

Here is an example of Javadoc



* Returns an Image object that can then be painted on the screen.

* The url argument must specify an absolute {

* argument is a specifier that is relative to the url argument.

* <p>

* This method always returns immediately, whether or not the

* image exists. When this applet attempts to draw the image on

* the screen, the data will be loaded. The graphics primitives

* that draw the image will incrementally paint on the screen.

*

*

*

*

*

*/

public Image getImage(URL url, String name) {

try {

return getImage(new URL(url, name));

} catch (MalformedURLException e) {

return null;

}

} /*** Returns an Image object that can then be painted on the screen.* The url argument must specify an absolute { @link URL}. The name* argument is a specifier that is relative to the url argument.* * This method always returns immediately, whether or not the* image exists. When this applet attempts to draw the image on* the screen, the data will be loaded. The graphics primitives* that draw the image will incrementally paint on the screen. @param url an absolute URL giving the base location of the image @param name the location of the image, relative to the url argument @return the image at the specified URL @see Image*/public Image getImage(URL url, String name) {try {return getImage(new URL(url, name));} catch (MalformedURLException e) {return null;

And the above would result in an HTML as follow when javadoc is run against the code that has the above

See here for more

Here are some key tags that you can use to enhance the quality of the generated java documentation.

@author => @author Raf

@code => {@code A<B>C}

@deprecated => @deprecated deprecation-message

@exception => @exception IOException thrown when

@link => {@link package.class#member label}

@param => @param parameter-name description

@return => What the method returns

@see => @see "string" OR @see <a ...></a>

@since => To indicate the version when a publicly accessible method is added

For a complete listing and more detailed description see here

Twitter’s coding standard advises against the use of @author tag

Code can change hands numerous times in its lifetime, and quite often the original author of a source file is irrelevant after several iterations. We find it’s better to trust commit history and OWNERS files to determine ownership of a body of code.

Following are examples of how you could write a documentation comment that is insightful as described in Twitter’s coding standard



// - The doc tells nothing that the method declaration didn't.

// - This is the 'filler doc'. It would pass style checks, but

doesn't help anybody.

/**

* Splits a string.

*

*

*

*/

List<String> split(String s); // Bad.// - The doc tells nothing that the method declaration didn't.// - This is the 'filler doc'. It would pass style checks, butdoesn't help anybody./*** Splits a string. @param s A string. @return A list of strings.*/List split(String s);

// - We know what the method splits on.

// - Still some undefined behavior.

/**

* Splits a string on whitespace.

*

*

*

*/

List<String> split(String s); // Better.// - We know what the method splits on.// - Still some undefined behavior./*** Splits a string on whitespace. @param s The string to split. An { @code null} string is treated as an empty string. @return A list of the whitespace-delimited parts of the input.*/List split(String s);

// - Covers yet another edge case.

/**

* Splits a string on whitespace. Repeated whitespace characters

* are collapsed.

*

*

*

*/

List<String> split(String s); // Great.// - Covers yet another edge case./*** Splits a string on whitespace. Repeated whitespace characters* are collapsed. @param s The string to split. An { @code null} string is treated as an empty string. @return A list of the whitespace-delimited parts of the input.*/List split(String s);

It’s important to be professional when it comes to writing comments

// Avoid (x)

// I hate xml/soap so much, why can't it do this for me!?

try {

userId = Integer.parseInt(xml.getField("id"));

} catch (NumberFormatException e) {

...

} // Prefer (✔️)

// TODO(Jim): Tuck field validation away in a library.

try {

userId = Integer.parseInt(xml.getField("id"));

} catch (NumberFormatException e) {

...

}