Introduction

    Coding conventions are very important for any programmer for various reasons as it has to be maintained for many years till the end of life cycle (EOL) of the software. Over the time multiple developers has to work on it and make the required changes either for fixing the bugs or for new enhancements. As it is almost impossible to maintain the software always by its original author for any software's lifetime, it is important to understand and follow the coding conventions while coding.

Why coding conventions are so important?

Coding conventions are important for many reasons.
  • More than 80% of cost of any software goes to maintenance.
  • Software is hardly maintained for its whole life by original author or coder.
  • Code conventions improve the code readability by allowing new programmers to understand the code quickly and properly.
  • If we follow all the conventions thoroughly, it also helps to generate proper documentation for the application which will help in future if we think of converting it as a product. Which saves lot of time and also helps in making further changes.

Different Conventions

  1. File Names
  2. Organization of Source File
  3. Formatting or Indentation
  4. Comments
  5. Declarations
  6. Statements
  7. White Space or Blank Space
  8. Naming Conventions
  9. Coding Practices
  10. Examples

1. File Names

  • For Java source file names usually use Camel Case as a standard with '.java' as filename extension.
  • Other sources files used in the project usually use lower letters for the file name (for ex: .properties, .xml, .json etc.) by using '_' (underscore) or '-' (hypen) to separate the word (for ex: application-dev.properties or application_dev.properties).
  • Folder or package names as well go with lowercase like other source files.
  • In some cases we can also use mnemonics or short forms as part of the file names to identify files based on the type of functionality, in some cases if the feature name is too large then some short names will be used to identify the feature to avoid big names for the source files. 

2. Organization of Source File

A file consists of different sections separated by blank line with optional comment to describe the respective section of the file or code. For better maintenance files with larger lines should be avoided. The files with less number of lines always better for maintenance. Files larger than 2000 lines should be avoided.

2.1 Java Source File

Every java source file contains a single public class or interface. Private classes and interfaces are associated with a public class kept under the same public class file. As per the code conventions the public class should be the first class or interface in the source file.

Following is the Java source file order:
  1. Beginning Comments or File Comments.
  2. Package and import statements.
  3. Class or interface declarations.

2.1.1 Beginning Comments or File Comments

All java source files should start with documentation style or c-style comments which should include,  class name, version information, Date of the file written or modified, copyright notice.

/*

 * Classname

 *

 * Version information

 *

 * Date

 *

 * Copyright notice

 */

 


2.1.2 Package and Import Statements

The first non-comment line in any java source file is package statement , below to this line  followed by import statements.

package java.awt; 
import java.awt.peer.CanvasPeer;

 


2.1.3 Class or Interface declaration

Below is the order of the sections for class or interface inside source file.
  1. Class or Interface documentation style comment (i.e. /** .... */ ). This comment is more about the purpose of class or interface.
  2. Class or Interface statement (i.e. the line which has class or interface keywords  for respective class or interface name)
  3. Class or Interface implementation comment if required (this is optional anyway, and the comment syntax is multiline comment, i.e. /* .... */). This contains the comment which is not appropriate for documentation comment. This mostly for class-wide or interface-wide information purpose.
  4. Static variables in the order: public, protected, default or package level and private variables.
  5. Instance variables in the order: public, protected, default or package level (no access specifier) and private variables.
  6. Constructors for the class.
  7. Methods- this is last section in any class or interface as per oracle code conventions for java. The methods should be grouped by functionality rather than scope or accessibility. The main goal is to make to understand the code in an easy way.

3. Formatting or Indentation

Now a days every IDE comes with most of the default setup for formatting of the code along with some additional setup. It is not that difficult like earlier days when we used to write code using notepad or some other tool where it was not that flexible. Most of the things we used to setup manually those days. Since now we have many tools like Eclipse, Intellij, Spring Tool Suite etc. which comes with all setup built within it. Unless you want some additional customization you can proceed with default setup for indentation or formatting.

Below details are to understand what code convention guideline says, it may help if we are creating some template for formatting our code. It will help to understand based on what details all these built-in formatting configured for java or any other source files.

Four spaces should be used as the unit of indentation (it can be done by using ‘tabs’ key from keyboard as well). Even though the exact indentation spaces unspecified tabs must be set exactly every 8 spaces as per java standards.

3.1 Maximum Line length

Try to keep maximum length of 80 characters per line, because many tools or terminals cannot handle it well if the length crosses more than 80 characters. But still we can try to check with current tools. But best convention is to use shorter lines.

3.2 Wrapping the Lines

If any of the expression won't fit in single line then break into multiple lines by following general principles as below:
  • Break the line a after comma
  • Break the line before an operator
  • Better to go with higher level breaks than lower level
  • Align new line with beginning of the expression at the previous line level.
  • If above indentation makes the code more confusing then better indent with 8 spaces instead.
Example-1 : Breaking method calls


exampleMethod(longExp1, longExp2, longExp3, 
        longExp4, longExp5); 
var = someMethod1(longExp1, someMethod2(longExp2,  longExp3));


Example-2: Formatting method declarations (Indentation)

//CONVENTIONAL INDENTATION
exampleMethod(int anArg, Object anotherArg, String yetAnotherArg,
           Object andStillAnother) {
    
}
 
//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
private static synchronized exampleLongMethodName(int anArg,
        Object anotherArg, String yetAnotherArg,
        Object andStillAnother) {
  

}


4. Comments

  1. Implementation comments (These are the one found in C++ which are delimited by /* .. */ and // .)
  2. Documentation comments (These are Java-Only comments and are delimited by /** … */, these comments can be extracted to html files with the help of Javadoc tool)
  • Comments should be used to give brief overviews of the code and to provide additional information which is not available in code. 
  • Comments should contain the only information which is required to understand the code better. 
  • Avoid duplicate comments or information which is already present. 
  • Avoid any comments that are likely to get outdated in future.
  • Comments should not be enclosed in large boxes drawn with asterisks (*) or other characters.
  • Comments should never include special characters such as form-feed(\f) and backspace(\).

Important NoteThe frequency of comments sometimes shows poor quality of code. So to avoid that consider rewriting the code to make it more clearer instead of adding many comments.

4.1 Implementation comments

These are meant for commenting out the code or for comments about particular implementation logic. Java has four styles of implementation comments.
  1. Block or Multiline comments
  2. Single Line comments
  3. Trailing comments
  4. End of Line comments

4.1.1 Block or multiline comments

Short comments can appear in a single line with proper indentation level, if comments won't fit in single line then it follows the block comment format with required indentation.

Example-1: Comment fitting in single line which fits along the code.

/*
 * This is block comment single line

 */


Example-2: comment not fitting in single line hence comes with manual indentation and ignored by auto indent due to mention of underscore after the asterisk at the beginning of the comment (/*_).

/*-
 * This is a block comment with some very special
 * formatting that tells indent(1) to ignore this
 * while formatting. 
 *    one
 *        two
 *            three

 */

4.1.2 Single Line Comments

Short comments are most of the time fit into single line along with proper indentation.

Example : Single line comment

if (Boolean-condition) { 
    /* Single line comment */
    ...

}