Java Style Guidelines


The objectives of this section are as follows :

  • To create developer independent source files and ease the job of program maintenance.

  • To make programs easier to read and understand.

In general, the source code should be self-documenting . The code should read like a book, where comments act as footnotes when a deeper explanation is needed. The format of the source code should follow a structured coding standard. All source files in the project should appear as if the same person wrote them. This makes software maintenance much easier. The coding standard should be well structured to allow the logic and flow to be easily identifiable. Lastly, identifier names should be written using English words.

Note

More information on coding standards is provided in the "Formatting" section later in this chapter.


Naming rules

Naming rules standardize the look and readability of the source code. The rules described in Table 4.1 provide a good starting point for most projects.

Table 4.1. The Naming Rules for Java Identifiers

Identifier

Naming Rule

Package

Express package names in lowercase.

 
 package com.mycompany; // NOT com.myCompany 

Class

Class names begin with a capital letter.

All words and acronyms within the name start with a capital letter.

If a class only exists to implement a single interface, the interface name should be appended to the class name.

 
 class MyClass // NOT class myClass 
 
 class MyActionListener // NOT MyActionClass 

Interface

Interface names begin with a capital letter.

All words and acronyms within the name start with a capital letter.

 
 interface MyInterface //NOT myInterface 

Exception classes

Exception classes follow the naming standard for class name. Additionally, all exception class names must end with the word "Exception".

 
[View full width]
 class HandleitException extends Exception // NOT graphics/ccc.gif class HandleIt 

Variables

Variables are nouns written in mixed case, starting with a lowercase letter.

 
 long bigCounter; //NOT long BigCounter 

Arrays

Arrays follow the same naming rules as other variables. The [] identifier is to be placed to the right of the array type, before the variable name.

 
 Object[] myObjs; //NOT Object myObjs[]; 

Methods

Methods are verbs using the same naming convention as variables.

All methods retrieving values must have names beginning with the word "get".

All methods changing attribute values must have names beginning with the word "set".

All methods returning Boolean values must have names beginning with the word "is".

All methods looking up collections of information must have names beginning with the word "find".

 
 int callNow() //Not int callnow() 
 
 int finaAllProducts() //NOT locateAllProducts() 

Constants

All letters in a constant's name must be capitalized with underscores ( _ ) separating the words.

 
 static String FIRST_NAME="Gerald"; // Not firstName 

Formatting

Formatting rules help standardize the layout of the source code. The following rules are sufficient for most projects:

  • No line is to exceed 80 columns per line. This promotes readability both on the screen and on printer output.

  • Do not include tabs or page breaks when formatting source files. These characters have different meaning on different platforms. Use a standard set number of spaces to represent tabs, for example four spaces.

  • The indentation increment is four spaces.

  • For lines of source code after the first line in multi-line statements, indent from the start of the first line.

  • Pick a standard for brackets and follow it. Typically starting brackets { lining up below ending brackets } provides the clearest demarcation .

  • When beginning a line with a // style comment, start in the same column as the line of code it applies to.

  • Use parentheses. Do not make the reader have to know and apply the order of precedence rules.

  • Use short names when the name scope is small. For example, if a StringBuffer object is used in a scope of a few lines of code, you can assign it to a variable name such as sb .

  • Use the += operator, instead of the = .. + .. construct. The += operator and its associated constructs execute slightly more efficiently and do not impair readability.

Comments and Documentation

Comments provide a mechanism to convey information about a program that cannot be done using the Java programming language. Ideally, comment usage should fall into the following five distinct categories:

  • Class or API documentation written using Javadoc.

  • Footnote style comments used to explain details not evident in the code. These are the comments that mix with the code, generally using the // comment at the end of the line.

  • Block comments are used for explaining what a group of statements is about to do.

  • To-do or notes comments that explain known bugs , describe future changes, and outline designs yet to be implemented.

  • /* and */ comments are often used to hide unused code. The final release of your source code should have very few, if any, of these comments.

Using Javadoc Comments

Javadoc comments consist of special delimiters and tags that when placed in source code can be used by the Javadoc utility to generate HTML pages describing classes, inner classes, interfaces, constructors, methods, and fields. That is, Javadoc enables you to create user documentation from source code comments. The generated HTML pages are available to other programmers on the project. Javadoc comments promote good communication between programmers and their usage is strongly recommended.

Note

More information on Javadoc can be found at http://java.sun.com/j2se/javadoc/.


Javadoc comments begin with a delimiter , /** and end with another delimiter, */ . The lines between these two delimiters consist of a description of the element and special tags that direct the Javadoc utility how to format the output. Because the generated output consists of HTML text, you are allowed to include HTML tags. The general form of Javadoc comments is given in Listing 4.3.

Listing 4.3 General Form for Javadoc Comments
 /** * Description * * @tag comment for the tag */ 

You should consider using the following Javadoc guidelines:

  • Document all non-inner classes and interfaces as in Listing 4.4.

  • Use the format shown in Listing 4.5 for inner classes, inner interfaces, and non-private instance variables.

  • Use the format shown in Listing 4.6 for non-private methods.

  • Use HTML tags for emphasis and text formatting. The following is a list of useful tags:

    To format source code use the <code> , </code> tags.

    Use <i> , </i> to italicize text.

    Use <b> to make text boldface.

    Use <p> to create empty paragraphs for spacing.

    Use <pre> , </pre> to display how text appears, with line breaks, spaces, and so on.

Listing 4.4 General Form for Class or Interface Javadoc Comments
 /** * * Descripion of class or interface * * @author Name of author. There can be multiple author lines. * @version Version and date string. Use the source code control's version number. * @see reference (you must have access to source code) */ 
Listing 4.5 General Form for Inner Class, Inner Interface, or Variable Javadoc Comments
 /** * * Descripion of inner class, inner interface, or variable. */ 
Listing 4.6 General Form for Non-private Methods Javadoc Comments
 /** * * Descripion of method * * @param param1 Description of first parameter. * @param param2 Description of second parameter. * @param paramn Description of nth parameter. * @return Description of return value. * @throws Exception class name. Conditions when exception is thrown. */ 

Java Source File Layout

The program layout is the pattern for how source code files should be constructed . Source code files should be based on a coding template. A sample template is presented in Listing 4.7.

The following elements are listed in the order they appear in the template file:

  • Standard header that includes your copyright notice

  • Package name

  • Import statements

Note

Import statements are ordered from general to specific as shown in the template in Listing 4.7. Also, only import the specific classes that are used by the application; avoid importing * from a package.


  • Class or interface

Note

Classes, interfaces, variables, and methods are further ordered according to their access modifier. Public identifiers are listed first, followed by protected, package, and then private.


  • Constants

  • Static instance variables

  • Instance variables

  • Static initializer

  • Instance initializer

  • Constructors

  • Methods

  • Finalizer method

  • Main method

Listing 4.7 Template for Program Structure
 /* * SourceTemplate.java * * Copyright 2000-2001 ThisCompany, Inc. * All rights reserved. * * This software is the confidential and proprietary information * of ThisCompany, Inc. ("Confidential Information"). You * shall not disclose such Confidential Information and shall use * it only in accordance with the terms of the license agreement * you entered into with ThisCompany. */ //package name package thiscompany.thisproject.thisapplication; //import java package //import javax package //import product API packages //import company API packages //import project specific API packages //import application specific API packages /** * * This sample source header file describes the structural layout of all Java * programs. You can include HTML within this section. In particular, * common use is made of * <i>italic</i> * <code> monospaced font for code</code> * <pre>display text how it appears, with spaces, line breaks, and so on</pre> * <b>boldface<b> <p> - empty paragraphs for spacing * * @author Joe Programmer * @version %I% %G% * @see Collection * @see Collections# sort * */ public class SourceTemplate { //Constants public static final String PUBLIC_CONSTANT="Public"; private static final String PRIVATE_CONSTANT="Private"; //Static variables private static int instanceCounter; //Instance variables //Static initializer //Instance initializer //Constructors /** * Constructs a new SourceTemplate with the command line arguments. * * @param args The command line arguments specifying the * work to be done * @throws Exception */ public SourceTemplate(String[] args) { } //Methods /** * Constructs a new SourceTemplate with the command line arguments. * * @throws Exception * @return Text message describing the final result */ public String execute() { return ""; } //Finalizer //Main /* This main is only for testing so I should not go into Java doc */ public static final void main(String[] args) { try { SourceTemplate st = new SourceTemplate(args); System.out.println(st.execute()); } catch(Exception e) { } } 


BEA WebLogic Platform 7
BEA WebLogic Platform 7
ISBN: 0789727129
EAN: 2147483647
Year: 2003
Pages: 360

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net