HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML
 

Coding style means nothing to a compiler; it will happily accept any legal code, no matter how badly formatted. Not so for us humans. Our ability to read and understand a program written by another is extremely sensitive to format. Imagine trying to read this article if every letter was in a different font and each line randomly aligned. Clearly, format affects readability, and it is just as true for reading programs as for text.

A consistent style also leads to lower maintenance costs by making it easier to debug and enhance the code. This is especially true for teams of programmers working on the same project, who must often read and edit each other's code. In this case, it is important that each team member follow not only a consistent style, but the same style. A common style also enables the development of automated tools to assist in program development, such as formatting tools and editor macros.

In spite of these benefits, some developers are reluctant to adopt a common style. One reason might be a belief that it requires too much effort. It is true that it takes a bit of time initially to learn the new rules (and unlearn old bad habits). However, once learned, they become automatic, and it takes no more effort to write code in a good style than in a poor style. In fact, it probably saves time by allowing programmers to concentrate on the semantics of the program, instead of consciously worry about the right format for each statement.

A larger reason for lack of a consistent style, however, is the lack of widely available, comprehensive and well thought out coding standards. This article is one attempt at improving this situation.

Space does not permit the presentation of an entire coding standard here. Rather, this article gives a selected set of the most important coding style rules, in somewhat condensed form. Listing 1 shows a code example demonstrating most of these style rules.

Indentation
One of the most important rules addresses the horizontal alignment of source lines.Line indentation is always four spaces per indentation level. [This is a difference from the predominant indentation style of eight spaces used in C programs; it is an acknowledgment that typical Java programs tend to have more levels of nesting than typical C programs.] The construction of the indentation may include tabs as well as spaces in order to reduce the file size; however, do not change the hard tab settings of your editor to accomplish this. Hard tabs must be set every 8 spaces. Soft tabs may be set every 4 spaces if your editor supports them.

Line Length
Lines should be limited to 80 columns. Longer lines should be broken into one or more continuation lines, as needed. All the continuation lines should be aligned and indented from the first line of the statement. The amount of the indentation depends on the type of statement.

If the statement must be broken in the middle of a parenthesized expression, such as for the parameter list in a method invocation or declaration, the next line should be aligned with the first character to the right of the first unmatched left parenthesis in the previous line. In all other cases, the continuation lines should be indented by a full standard indentation (4 spaces).

Braces Style
The preferred style for placement of braces in compound statements is the style commonly referred to as the "K&R" style. [Named after Brian Kernighan and Dennis Ritchie, authors of the first book on the C language.] Unlike C, in Java this style is used in all cases, including class and instance initializers and array initializers. This style is specified as follows:

  1. The opening left brace "{" is at the end of the line beginning the statement.
  2. The closing right brace "}" is alone on a line, indented to the same column as the first line of the statement.
  3. The statements inside the enclosed braces are indented one more level than in the statement.
Naming Conventions
Another aspect of coding style that makes a big difference is consistency of naming. Package names should use only lower-case letters and digits, and no underscore. If the package will be publicly distributed, prepend a unique prefix to the package by using the Internet domain name components in reverse order (e.g., com.sun, graphics.util).

All class and interface names should use the InfixCaps style. Start with an upper case letter and capitalize the first letter of any subsequent word in the name. All other characters in the names are lower case. Do not use underscores to separate words. Class names should be nouns or noun phrases. Interface names depend on the purpose of the interface. If it is primarily to endow an object with a particular capability, then the name should be an adjective that describes the capability (e.g., Searchable, Sortable). Otherwise, use nouns or noun phrases.

Variables (except static final types, see below) use the infixCaps style. Start with a lower case letter and capitalize the first letter of any subsequent word in the name, as well as any letters that are part of an acronym. all other characters in the name are lower case. Do not use underscores to separate words. Variable names should be nouns or noun phrases (e.g., numberOfPoints).

Static final primitive types being used as constants should be all upper case, with underscores separating words (e.g., MAX_BUFFER_SIZE).

Method names also use the infixCaps style. Method names should be verbs or verb phrases (e.g., drawCircle()).

White Space Usage
Blank lines can improve readability by grouping sections of the code that are logically related. A blank line should also be used:

  • After the package declaration and import section
  • Before a class or method declaration
  • Before a block or single-line comment, unless it is the first line in a block.
A single blank space (not tab) should be used to separate all tokens in a statement, except for the following. Blanks should not be used:
  • Between a constructor or method name and its opening parenthesis
  • Before or after a . (dot) operator
  • Between a unary operator and its operand
  • Between a cast and the expression being casted
  • After an opening parenthesis or square bracket, or before a closing parenthesis or square bracket
Comments
Comments can help the reader understand the code. Here are some general guidelines for comment usage:
  • Comments should help a reader understand the purpose of the code. They should guide the reader through the flow of the program, focusing especially on areas which might be confusing or obscure.
  • Avoid comments that are obvious from the code, as in the famously bad comment example:

i=i+1; //Add one to i

  • Remember that misleading comments are worse than no comments at all.
  • Avoid putting any information into comments that is likely to become out-of-date.

About the Author
Achut Reddy is the Project Lead for Java Performance Tools at Sun Microsystems in Menlo Park, CA. Achut has been with Sun for 9 years and has worked on a number of products, including Java WorkShop, C/C++ Workshop and SPARCworks. He received his degree in Computer Engineering from UCLA and has worked in the software industry for 15 years.

	

Listing 1
  
Example code demonstrating coding style rules)  
/*  
 * @#CodingStyleExample.java        1.0 98/01/23 Achut Reddy  
 *  
 * Copyright (c) 1994-1998 Sun Microsystems, Inc. All Rights Reserved.  
 */  
package com.sun.examples;  

import java.applet.Applet;  
import java.awt.Point;  
/**  
 * A class to demonstrate good coding style.  
 */  
public class CodingStyleExample extends Applet implements Runnable {  
    static final int            BUFFER_SIZE = 4096;    // default buffer size  
    StringBuffer             name;                                  // my name  
    Point                         starshipCoordinates[];        // ship locations  
    /**  
     * Compute the total distance between a set of Points.  
     * @param starshipCoordinates the locations of all known starships  
     * @param numberOfPoints      the number of points in the array  
     * @return the total distance  
     */  
    public int computeDistances(Point starshipCoordinates[],  
                                int numberOfPoints) throws Exception {  
        int     distance = 0;   // accumulates distances  
        // Compute distance to each starship and add it to the total  
        for (int i = 0; i < numberOfPoints; i++) {  
            distance += Math.sqrt((double)((starshipCoordinates[i].x *  
                                            starshipCoordinates[i].x) +)  
                                            (starshipCoordinates[i].y *  
                                            starshipCoordinates[i].y)));  
        }  

        if (distance > 100000) {  
            throw new Exception  
        }  

        return distance;  
    }  
    /**  
     * Called whenever Thread.start() is called for this class  
     */  
    public void run() {  
         try {  
              name.append  (X);  
              System.out.println(name);  
         } catch  (Exception  e) {  
              name = new StringBuffer(BUFFER_SIZE);  
         }  
     }  
}  
 
      
 

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: info@sys-con.com

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.