Resources‎ > ‎Java Basics‎ > ‎

Style Guidelines

Code readability and maintainability are both incredibly important. It is essential that you develop a consistent coding style for yourself as well as anyone who may look at your code in the future. Below are a few common guidelines that you should incorporate into your code.

Excerpts from Java Software Solutions 5th edition by Lewis&Loftus (Appendix F)

Identifier Naming

Method and variable names generally start with a lowercase letter and class names normally start with an uppercase letter. Identifiers are often a multi-word description of what they are identifying, and uppercase letters are used to specify word breaks. For example, a variable representing a first name might be called firstName. A class representing a bank account might be called BankAccount.

Indentation

Code between an open brace ({) and the corresponding close brace (}) should be indented a consistent number of spaces. This applies to if statements, loops, method definitions, and class definitions. The close brace should always be lined up with the header of the statement. L&L suggest that the open brace be on a new line, however putting the open brace at the end of the header line is also common. Choose your own style, and be consistent!

Examples:
if(firstName.equals("Bob")) 
{
//all code indented by the same amount
System.out.println("Short for Robert?");
System.out.println("Or is that your full name?");
}

public static void main(String[] args) { //open brace at the end of the header line
//all code indented by the same amount
System.out.println("Hello, world");
}
Spacing

  • Put one space after each comma in a parameter list.
  • Put one space on either side of a binary operator.
  • Do not put spaces immediately after a left parenthesis or before a right parenthesis.
  • Do not put spaces before a semicolon.
  • Put one space before a left parenthesis, except before an empty parameter list.

Documentation

  • Every source code file should contain a header block of documentation providing basic information about the contents and the author.
  • Each class and interface, and each method in a class, should have a small header block that describes its role.
  • Use in-line documentation as appropriate to clearly describe interesting processing.
  • Don't wait until a program is finished to insert documentation. As pieces of your system are completed, comment them appropriately.
Comments