The Otego AG Java Coding Standard

$Revision: 1.9 $, $Date: 2002/03/18 07:18:47 $, Last changing $Author: giacomo $


Table of Contents

Introduction

Code standards aren't just about obsession, they are about productivity, professionalism, and presentation. This code standard for Java is adhered to by the Otego AG so that our resulting product is more readable, maintainable, robust, testable, and professional.

Many people helped with the evolution of this code standard. These practices were not created in a vacuum. They are tried and true rules that have been used in producing both research and commercial systems by teams of dozens of programmers. While not all the rules are applicable to every developer or all systems, a general adherence to the rules and a belief in software engineering practices often results in happier and healthier developers and systems.

Structure

In the context of this document, "structure" means "organization, look, and feel" of a body of code. It includes elements of system and subsystem organization (packages), documentation (Javadoc tags, inline comments, and index files), specification (more Javadoc tags, running comments, index files), and development (code organization). Adhering to these standards means that every piece of code has the same structure so that a reader can instantly know where to find a piece of information (attribute, import, method, etc.) without have to search through an entire source file.

Packages

Create a new Java package for each self-contained project or set of related functionality, in accordance with the following package naming guidelines (including a directory structure which corresponds to the package naming, as per Java conventions):

Provide a package.html file in each package directory briefly outlining the purpose and structure of the package. This file is used by Javadoc (in Java 1.2 and later) as package commentary, and also serves as local documentation for your code tree. For more information on the format of this file as used by Javadoc, see the package-level comments documentation on Sun's web site. If you plan to allow local browsing of your source tree, you should alias this file to index.html so that it serves as the default index file for the directory.

Program Files

Place each and every class in a separate file. This applies even to non-public classes (which are allowed by the Java compiler to be placed in the same file as the main class using them), except in the case of one-shot usages where the non-public class cannot conceivably be used outside of its context. One example of such usage is the creation of Event classes in AWT 1.1 programming.

Begin each file with a comment block containing at least the following information (example below):

  1. Any copyright information relevant to the project.

Immediately follow the file header with:

Example file header:


/*****************************************************************************
 * Copyright (C) 2002 Otego AG, Switzerland. All rights reserved.            *
 * ------------------------------------------------------------------------- *
 * This software is published under the terms of the otego Software License  *
 * version 1.0, a copy of which has been included with this distribution in  *
 * the LICENSE file.                                                         *
 *****************************************************************************/

package com.otego.project.sample;

import com.otego.project.otherpackage.FooObject;
import com.otego.project.otherpackage.MyObject;

import com.otego.otherproject.somepackage.MyObject;

import javax.management.timer.TimerMBean;
import javax.xml.parsers.SAXParser;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.Vector;

Classes and Interfaces

Write all /** ... **/ comments using Javadoc conventions. Even though it is not required by Javadoc, end each /** comment with **/ to make it easier to read and check.

Preface each class with a /** ... **/ comment describing the purpose of the class, guaranteed invariants, usage instructions, and/or usage examples. The beginning of the comment should be a description of the class in exactly one sentence. Also include any reminders or disclaimers about required or desired improvements. Use HTML format when appropriate, but do not forget that all inline text is parsed as HTML format, so accidental use of HTML elements can result in strange looking documentation. See the below chart for appropriate tags and usages.

Each class comment block must include exactly one @version tag and at least one @author tag. The @author tags often list everyone who has written more than a few lines of the class. Each @author tag should list exactly one author including its email address. The @version tag's version is a project specific string (e.g. "${version}") which will be replaced by Jakarta Ant (our preferred project building tool) followed by a CVS/RCS $Id$ tag. Additionally, each class can optionally contain a // comment after its closing brace stating that the class declaration has ended.

Example class comment block:


<file header, package name and imports, as above>

/**
 * A class representing the archetypical class from which one can
 * learn code standards through example.
 *
 * Usage example:
 * <CODE>
 * 	ArchetypeClass ac = new ArchetypeClass();
 *	ac.init();
 * </CODE>
 *
 * @see     ArchetypeAbstractClass
 * @see     ArchetypeInterface
 * @see     java.lang.Object
 * @version ${version} $Id: java_standard.html,v 1.9 2002/03/18 07:18:47 giacomo Exp $
 * @author <a href="mailto:giacomo.pati@otego.com">Giacomo Pati</a>
 * @author <a href="mailto:martin.biel@otego.com">Martin Biel</a>
 **/

public class ArchetypeClass extends AnotherClass
    implements FooInterface, BarInterface
{
  ...
}

// end of class ArchetypeClass

Class (Static)/Instance Fields

Use Javadoc conventions to describe the nature, purpose, constraints, and usage of static fields and instance fields. See the chart below for appropriate tags and usages. All static fields should appear together, before the set of method declarations; all instance fields should likewise appear together, after the set of static fields (but always before the method declarations). The sets of static and instance fields should be clearly offset by comments (the format of these comments is left to the individual programmer, though they should be clear).

For real OO-programming there is never a use of public instance variables. Those should be made available by use of getter and setter methods. Also, the convention for protected and public instance variables should be to prefix them with 'm_' to clearly show this fact. Why this? Simply because instance variables are potentially risky in the server-side programming concerning thread safetiness.

For example:


public class Example
{
    // Static Fields

    /**
     * This is a static field.
     **/

    priivate static String m_staticString = "Static String";


    // Instance Fields

    /**
     * This is an instance field.
     **/

    protected String m_instanceString = "Instance String";


    // Method Declarations

    ...
}

Methods

Method parameters should be cleanly organized, either on a single line or one per line. All static methods should appear together; the same goes for instance methods. These blocks of methods should be clearly delineated with comments (as for blocks of variables, above). Some examples of acceptable method declarations:


  public static int aMethod( final String aString, final int anInt, final double aDouble );

  public synchronized Exception anotherMethod( final String aString,
                                               final int anInt,
                                               final double aDouble );

  public final Event yetAnotherMethod(
      final Long aLongObject, 
      final String aString, 
      final Double aDoubleObject );

                                       

Whenever possible use the final modifier for variables, methods and arguments. This enable the most performance optimization and security constraints possible.

Use Javadoc conventions to describe nature, purpose, preconditions, effects, algorithmic notes, usage instructions, reminders, etc. The beginning of a method comment should be a summary of the method. Use HTML format when appropriate. See the chart below for appropriate tags and usages.

In all of the following tags, Expression means (OCL-Expression | code segment | natural language description). An OCL-Expression is an expression in the Object Constraint Language; see Joe for more information. A code segment is a legal expression from any programming language, but is most often written in the language of the code it documenting, in this case Java. A natural language description is a description written in a spoken language (like English).

For all tags, entities enclosed in () or <> must be so enclosed when using the tags. E.g. "(Expression)" means literally "(" + the expression + ")". Entities enclosed in [] in the table indicate optional entities and should not use literal square brackets.

The table lists, in the "Usage" column, the Java entities to which each tag is applicable. Possible values for this column are classes, interfaces, methods, fields (that is, instance fields and static fields of a class or interface), all (which means "classes, interfaces, methods and fields"), and special (special usages explained in the "Purpose/Description" column).

More detailed information on the syntax of the standard Javadoc tags described here (most notably, @see, {@link} and the serialization-related tags) is available from Sun's Javadoc Home Page.

Javadoc Tag Conventions

Tag Usage Purpose/Description
Meta-Information
@author <a href="mailto:authors.mail@address.link>>Full Name</a> Classes, Interfaces Lists an author of the class or interface. The text has no special internal structure. A doc comment may contain multiple @author tags. A standard author tag includes only the full name of the author and should not include other information (like an email address, web page, etc.) unless absolutely necessary.
@history Description All Describes how a feature has been significantly modified over time. For each major change, the description should include: who made it, when it was made (date and version), what was done, why it was done, and a reference to the change request and/or user requirement that resulted in the change being made.
Pending Work
@bug Description Classes, Interfaces, Methods Describes a known bug in the class or method. One tag should be used for each bug. If a construct has a known bug, it should be described. Omission of a bug description is considered as bad an offense as the existence of the bug in the first place.
@review Username - Description All Suggests/Reminds a reader that a particular block of code still needs to be reviewed (by the named user) for some reason. Typical reasons include the "something's not right here" syndrome, boundary condition checks, not understanding an algorithm completely, etc.
@todo Username - Description All Describes some work that still needs to be accomplished by the named user. Typical examples include optimizing algorithms, proving correctness of new code, renaming fields or methods to conform to standards, cleaning up code, etc.
@idea Username [Classifier] - Description All Describes an idea for something from the named user. The optional <classifier> argument is for ad hoc categorization of ideas. Typical examples include optimizing algorithms, proving correctness of new code, renaming fields or methods to conform to standards, cleaning up code, etc.
Preconditions
(@precondition | @pre) (Expression) [<Throwable> -] [Description] Methods Describes a precondition which must be true before the method can be safely invoked. One tag is used for each precondition. If a precondition is violated Throwable is thrown.
@requires (Expression) Description All Describes assumptions about execution context. In particular, describes any reliance on actions in other threads to terminate or provide notifications. Requires expressions are usually not expressible in code and cannot be tested at runtime.
Postconditions
(@postcondition | @post) (Expression) [<Throwable> -] Description Methods Describes a postcondition which is true after a method has completed, successfully or not. If a postcondition is violated Throwable is thrown. Postconditions that throw exceptions interact with the standard Java exception mechanism and thus are described in the @exception tag. One tag is used for each postcondition.
@ensures (Expression) Description Classes, Methods Specifies the semantics of an element's behavior and any guarantees it makes. Ensures expressions are usually not expressible in code and cannot be tested at runtime.
@generates (Expression) [Description] Classes, Methods Describes new entities (for example, Threads) constructed as a result of the execution of a method or the instantiation of a class.
@modifies (SINGLE-ASSIGNMENT | QUERY | Expression) Description All Indicates the semantics of a construct as follows:
  • SINGLE-ASSIGNMENT indicates that the construct will be set or operated upon exactly once. Once the variable is set or the method is called, it will never be set or called again.
  • QUERY indicates that the construct is read-only and has no side-effects.
  • Expression indicates that a method modifies an object and describes how it does so.
Invariants
@invariant (Expression) [<Throwable>] Description Classes, Interfaces, Methods Specifies a class, interface or method invariant. An invariant is an expression which must evaluate to true whenever the entity being described is in a stable state. An invariant expression must evaluate to a boolean.

An object is defined as being in a stable state when either (a) no threads of control are within the object or operating upon the object, (b) a single thread of control is about to enter a method of the object, or (c) a single thread of control is about to exit a method of the object.

If an invarient is violated when an object is in a stable state, a Throwable is thrown.

Concurrency Control
@concurrency (SEQUENTIAL | GUARDED | CONCURRENT | TIMEOUT <value> <Throwable> | FAILURE <Throwable> | SPECIAL) [Description] All Describes the concurrency strategy and/or approach taken by (necessary for) the class/interface/method (field). The execution context for a method should be described at this point. The meanings of the possible parameters are as follows:
  • SEQUENTIAL means that callers must coordinate so that only one call/access to the object in question may be outstanding at once. If simultaneous calls occur, the the semantics and integrity of the system cannot be guaranteed.
  • GUARDED means that multiple calls/accesses from concurrent threads may occur simultaneously to one object in question, but only one is allowed to commence; the others are blocked until the performance of the first operation is complete. This is the behavior of synchronized methods.
  • CONCURRENT indicates that multiple calls/accesses from concurrent threads may occur simultaneously to the object in question. All will proceed concurrently with correct semantics. Note that this is the default mode of Java methods and fields, unless otherwise indicated.
  • TIMEOUT <value> indicates that if a call to this method is blocked for a time period greater than or equal to <value>, the exception <Throwable> will be thrown.
  • FAILURE means that if a call to the method is currently underway, all additional calls with fail and the exception <Throwable> will be thrown.
  • SPECIAL indicates that the method has concurrency semantics that are not covered by the preceding three cases. Make sure to explain the particulars of the method's semantics in sufficient detail that the reader will be quite clear on your method's unusual semantics.

A method lacking a concurrency tag is considered CONCURRENT. The semantics description is optional on methods which are tagged as SEQUENTIAL or GUARDED. In general, all methods should have concurrency tags.

Java Usage Information
@param parameter-name [WHERE (Expression)] Description Methods Describes a method parameter. The description may be continued on the following line(s). The expression indicates restrictions on argument values. Restrictions that result in exceptions, for example IllegalArgumentException, should be indicated as such. In particular, it is important to indicate whether reference arguments are allowed to be null. There must be one @param tag for each and every parameter to the method.
@return Description Methods Describes a method's return value. The description may be continued on the following line(s). If the method being documented is a simple getter method (or similar), a @returns tag is still necessary; however, in such a case, the actual method description may be omitted (since the @returns tag completely describes the method).
@exception ExceptionClassName [IF (Expression)] Description Methods Describes an exception which can be thrown by the method, and the circumstances under which it is thrown. The exception is linked to its class documentation. The guard indicates restrictions on argument values. In particular, it is important to indicate whether reference arguments are allowed to be null. There must be one @exception tag for each and every exception declared to be thrown by the method; in particular, if a RuntimeException such as IllegalArgumentException is declared in the method signature, it must be documented. It is generally a good idea to declare in the method signature any runtime exceptions which are thrown as a result of conditions controllable at compile-time (such as the method being called in the wrong system state, or a lack of sufficient range checking on passed argument values).
Versioning
@version Version-String $Date$ Classes, Interfaces Denotes the version of the class. The text has no special internal structure. A doc comment may contain at most one @version tag. The @version tag normally refers to the version of the software project which contains this class, rather than the version of this particular class.
@deprecated Reference to replacement API. All Indicates that this API should no longer be used (even though it may continue to work). By convention, the text describes the API (or APIs) which replace the deprecated API. For example:

    @deprecated Replaced by setBounds( int, int, int, int ).

If the API is obsolete and there is no replacement, the argument to @deprecated should be "No replacement".

@since version-tag All Indicates the (release) version number in which this feature first appeared. This version number, like that for @version, is usually a project-wide version number rather than a version number for the particular class in which the feature appears. No @since tag is required for features which have existed since the first version of the project.
Inheritance
@hides FullClassName.FieldName [Description] Fields Indicates that a particular field hides a field in a parent class. For example:

  /**
   * @hides java.util.Vector.elementCount
   **/

  protected long elementCount = 0;
    

@overrides FullClassName.MethodName() [Description] Methods Indicates that a particular method overrides a method in a parent class. For example:

  /**
   * @overrides java.util.Vector.clone() We need to provide a deep clone. 
   **/

  public synchronized Object clone();

If the overriding method does not either call or implement a superset of the semantics of the method it overrides, its effects must be documented (using precondition/postcondition/invariant tags and the method description, as appropriate).
Documentation
@equivalent (Expression | Code Reference) Classes, Interfaces, Methods Documents convenience or specialized methods which can be defined in terms of a few operations using other methods.
@example Description All Provides one or more examples of how to use a given class, interface, method, or field. This helps developers to quickly understand how to use your classes.
@see APIName Label All Adds a hyperlinked "See Also" entry to the class documentation. APIName can be the name of a Java API or an HTML anchor. Some examples (with their appearance in Javadoc in comments on the right-hand side) are:

@see java.lang                          //  java.lang
@see java.lang.String                   //  String 
@see java.lang.String The String class  //  The String class
@see String                             //  String
@see String#equals( Objetc )            //  String.equals( Object )
@see String#equals                      //  String.equals( java.lang.Object )
@see java.lang.Object#wait( long )      //  java.lang.Object.wait( long )
@see Character#MAX_RADIX                //  Character.MAX_RADIX
@see <A HREF="spec.html">Java Spec</a>  //  Java Spec       

This Javadoc tag is often used to reference an external document which describes pertinent business rules or information relevant to the source code being documented.

The character # separates the name of a class from the name of one of its fields, methods, or constructors. One of several overloaded methods or constructors may be selected by including a parenthesized list of argument types after the method or constructor name. Whitespace in @see's classname is significant. If there is more than one argument, there must be a single blank character between the arguments. For example:

      
    @see java.io.File#File( java.io.File, java.lang.String )

A doc comment may contain multiple @see tags.

{@link APIName Label} All Adds an inline link to other documentation. This tag begins and ends with curly braces to seperate it from the rest of the inline text. It accepts exactly the same syntax for APIName and Label as the @see tag. A doc comment may contain multiple {@link} tags.
Design
@design Description All Provides information about design decisions you have made and/or useful things to know about parts of your code.
Serialization
@serial Description Special Describes the purpose of and acceptable values for a seriable field. This tag can only be used on default serializable fields (instance fields, of classes which implement Serializable, which are not declared to be transient). There is no specific format for the description. This information is used by Javadoc to build pages describing the serialization behavior of the class.
@serialField Field-Name Field-Type Description Special Documents an ObjectStreamField component of the serialPersistentFields member of a Serializable class. This tag can only be used for such components, and one tag should be used for each. The "Field-Name" and "Field-Type" fields should be the name and class of the field, respectively; there is no specific format for the description. This information is used by Javadoc to build pages describing the serialization behavior of the class.
@serialData Description Special Documents the sequences and types of data written by the class's writeObject and/or writeExternal methods as part of object serialization. This tag can only be used in the doc comments for the writeObject, readObject, writeExternal, and readExternal methods. This information is used by Javadoc to build pages describing the serialization behavior of the class.
Dependencies
@references (Expression) [Description] Classes, Methods, Fields Indicates that the class or attribute references other constructs like objects, instances, files, etc. This is primarily used to indicate subtle interdependencies between classes, instances, etc.
@uses (Expression) [Description] All Indicates exactly which elements are utilized by this element. This tag is primarily used to indicate hidden dependencies.
Miscellaneous
@guard (Expression) [Description] Methods Indicates that actions use guarded waits until the condition specified in Expression holds.
@values (Expression) [Description] Fields Describes the possible values of a field, including ranges and/or distinct values.
@complexity (Expression) [Description] Methods Documents the time or space complexity of a method. Expression should be in big-O notation, but doesn't have to use proper Java syntax. E.g. O(n*n) and O(n^2) are equivalent, but the second is the more normal way to express a square term. Normally the free terms of the expression are documented in the description and are usually related directly to instance variables of the surrounding or related class.

Always be as precise as reasonably possible in documenting effects.

Code Layout

A consistent code layout style improves code readability, maintainability, and robustness. We use xemacs for automatic code layout. Our code layout rules are as follows:

XEmacs-specific Code Standard Support

The following elisp code expressions can be added to your .xemacs/init.el startup file to institute all of the above standards (except the brackets for every block of code in a conditional or loop) automatically. Note that, in fact, it is actually much safer just to take someone's working .xemacs/init.el file and customize it for yourself. This way, subtle dependencies in the setup are handled.

Here is the elisp code:


;; Indentation Settings

;; preload cc-mode to make settings
(require 'cc-mode)

;; indents are in blocks of two spaces
(setq-default c-basic-offset 4)

;; make sure we don't use tabs in indents
(setq-default indent-tabs-mode nil)

(cond ((or (string-match "4." c-version)
           (string-match "5." c-version))

       ;; Setup for CC-mode version 4 and above.
       
       ;; Set up indention for programming in C, C++, Objective C, and
       ;; Java

       (defun c-lineup-javadoc-comments (langelem)
         ;; Define a new custom indentation function for handling
         ;; Javadoc comments.  Line up all first *'s.  First create a
         ;; new context so the point, mark, and current buffer are not
         ;; munged, even in the case of abnormal exit.
         (save-excursion
           ;; goto the point that is defining our indention depth
           (goto-char (cdr langelem))
           ;; is it the first line of a javadoc comment?
           (if (looking-at "/\\*")
               ;; yes! so return a 1
               1
               0)))

       ;; We define a new CC-mode style for our group's code standards.
       ;; We'll call this style "caltech-java".
       (defconst caltech-java-style
           '((c-basic-offset . 2)
             (c-comment-only-line-offset . (0 . 0))
             (c-offsets-alist . 
              ((access-label          . 0)
               (arglist-close         . c-lineup-arglist)
               (arglist-intro         . c-lineup-arglist-intro-after-paren)
               (c                     . c-lineup-javadoc-comments)
               (case-label            . +)
               (inher-cont            . c-lineup-java-inher)
               (inline-open           . 0)
               (knr-argdecl-intro     . 5)
               (label                 . +)
               (statement-case-open   . +)
               (statement-cont        . 0)
               (substatement-open     . 0)
               (statement-block-intro . +)
               (topmost-intro-cont    . +)))))

       ;; Customizations for all c-mode, c++-mode, objc-mode, and java-mode.

       (defun caltech-java-mode-hook ()
         "Hooking in the Caltech Infospheres code standard for CC-mode
version 4 and turning on cc mode's minor modes."
         ;; Add caltech-java style and set it for the current buffer.
         (c-add-style "caltech-java" caltech-java-style t)
         ;; Add any user-specific customizations here (should be none).
         ;;
         ;; CC Mode has two minor modes; auto-newline and hungry-delete.
         ;; If you don't like the behavior of either of these minor modes,
         ;; comment out the following expression.  More information on
         ;; these minor modes is available in the CC Mode info pages.
         (c-toggle-auto-hungry-state 1)
         ;; Keybindings for all supported languages can be added here.
         ;; We can upt these in c-mode-map because all the other maps
         ;; inherit from it.
         ;; (define-key c-mode-map <key> <func>)
         )

       ;; Add hook to Java mode to start everything up everytime we
       ;; enter a Java buffer.
       (add-hook 'java-mode-hook 'caltech-java-mode-hook))

      ((string-match "3." c-version)

       ;; Customization for CC-mode version 3.
       ))


The following elisp code expressions can also be added to your .xemacs/init.el startup file to check your current xemacs buffer according to the coding convention stated in this document by use of a customized checkstyle tool.



Documentation

What's the point?

Documentation is all about communication. If you have any hope or desire to see your code understood and reused, it needs to be completely and thoroughly documented.

How much is enough?

Your guiding metric for "How much is enough?" should be the following: Communicate exactly enough information in your comments to the reader so that they could implement what you are describing and do so correctly.

Self-documenting code

Some argue that the code itself should be "self-documenting". This is true, in some sense, and we enforce it in some ways through naming conventions and running comments, but it isn't enough. What about the reader who doesn't know the language you are coding in? What about proprietary reusable components? Obviously, something more is necessary.

Real coders don't document

Also, for those of you that think that documenting is for weaklings and that real hackers/masters/Rambo-coders don't need comments; believe us, we could find some code that you wouldn't understand even with days of head-scratching (if you're in the area, drop by and we'll prove it). Rambo-coders need not apply.

Local declarations, statements, and expressions

Use /* ... */ comments only to temporarily comment out blocks of code. Otherwise, only C++-style (//) comments should be used to describe algorithmic details, notes, and related documentation which spans more than a few code statements.

Example:

   
    // Strategy:
    // 1. Find the node
    // 2. Clone it
    // 3. Ask inserter to add clone 
    // 4. If successful, delete node
    

Use running // comments to clarify non-obvious code. However, always prefer making the code more obvious to commenting it because it is non-obvious, and don't bother commenting obvious code.

Example:


    int index = -1; // -1 serves as flag meaning the index isn't valid

Or, even better:


    static final int INVALID= -1; 
    int index = INVALID;

Naming Conventions

You can name your temporary and loop variables anything you like, (we suggest prefixes of temp and loop), but all your other variables, especially static and instance fields of your objects, must have some sort of uniform naming scheme. The follow specification of naming standards follows the conventions of several organizations and individuals. It has been created by committee, however, so it probably won't completely satisfy or dissatisfy any individual.

Element Type Convention Examples and Comments
Package All lowercase Use the recommended domain-based conventions described in the Java Language Specification, page 107 as prefixes. (For example, com.otego.projectname.)
File Compiler-enforced The java compiler enforces the convention that file names have the same base name as the public class they define.
Class Capitalize all subwords DjinnMaster, BillTheCat, MyClass, PokerPlayer
Abstract Class Same as Class, but starting with Abstract AbstractDjinn, AbstractCat, AbstractClass, AbstractPlayer
Factory Class Same as Class, but ending with Factory DjinnFactory, CatFactory, ClassFactory, PlayerFactor
Class Implementation Same as Class, but either ending with Impl or be prefixed with the a name which states its concrete implementation DjinnImpl, CatImpl, SiamCat, ClassImpl, MyClass, PlayerImpl, DefaultPlayer
Exception Same as Class, but ending with Exception DjinnException, CatException, ClassException, PlayerException
Interface Same as Class, it may have a Interface or -able suffix DjinnInterface, CatInterface, Runnable, RemoteLoadable, Manager
Constant All capital letters with embedded underscores DJINN_MAX_WEIGHT, CAT_FUR_LENGTH, CLASS_SIZE, PLAYER_NUM_FINGERS
Instance Field Initial letter is lowercase, all other subwords are capitalized. DjinnName djinnName, BillTheCat bill, Class myClass, PokerPlayer aPlayer
Method Initial letter is lowercase, remaining subwords are capitalized. callDjinn(), kickCat(), twiddleClass(), pokePlayer()
Converter Method Initial lowercase word is "to", remaining subwords are capitalized. toGenie(), toTiger(), toAbstractClass(), toBridgePlayer()
Getters (methods that query state) Initial lowercase word is "get", remaining subwords are capitalized and, if possible, are exactly the same as the name of the instance field to which they relate. getDjinnName(), getCatColor(), getClassSize(), getPlayerBank()
Setters (methods that set state) Initial lowercase word is "set", remaining subwords are capitalized and, if possible, are exactly the same as the name of the instance field to which they relate. setDjinnLocation(), setCatSex(), setClassLoader(), setPlayerLuck()

Test Case

Consider writing a JUnit TestCase class for each class of group of related classes. The TestCase class should provide a unit test. These TestUnit classes should be executed in the Ant build script to have consistent regression tests available.

TestCases for Avalon Components usually extend the org.apache.avalon.excalibur.testcase.ExcaliburTestCase class which creates an Avalon environment including a ComponentManager, LogKit configuration, and Component Configuration for your Components.

Recommendations

The following are coding recommendations. It is not necessary to follow them to the letter, but we have found it helpful to always keep them in mind.

Do not use the * form of import. Be precise about what you are importing. Check that all declared imports are actually used.
Rationale: Otherwise, readers of your code will have a hard time understanding its context and dependencies. Some people even prefer not using import at all (thus requiring that every class reference be fully dot-qualified), which avoids all possible ambiguity at the expense of requiring more source code changes if package names change. (We, however, aren't that freaky.)

For standalone application programs, the class with the main() method should be separate from those containing normal classes.
Rationale: Hard-wiring an application program in one of its component class files limits the potential for class reuse.

If you can conceive of someone else implementing a class's functionality differently, define an interface rather than an abstract class. Generally, use abstract classes only when they are "partially abstract"; i.e., they implement some functionality that must be shared across all subclasses.
Rationale: Interfaces are more flexible than abstract classes. They support multiple inheritance and can be used as "mixins" in otherwise unrelated classes.

Consider carefully whether any class should implement the Cloneable and/or Serializable interfaces.
Rationale: These are "magic" interfaces in Java, that automatically add possibly-needed functionality only if so requested.

Declare a class as final only if it is a subclass or implementation of a class or interface declaring all of its non-implementation-specific methods (a similar principle applies to the declaration of final methods).
Rationale: Making a class final means that no one will ever get a chance to reimplement its functionality. Defining it instead to be a subclass of a base that is not final means that someone at least gets a chance to subclass the base with an alternate implementation, which will essentially always happen in the long run.

Never declare instance fields as public.
Rationale: The standard OO reasons. Making fields public gives up control over internal class structure. Also, if fields are public, methods cannot assume that they have valid values.

Minimize statics (except for static final constants).
Rationale: Static fields act like globals in non-OO languages. They make methods more context-dependent, hide possible side-effects, sometimes present synchronized access problems. and are the source of fragile, non-extensible constructions. Also, neither static fields nor static methods are overridable in any useful sense in subclasses.

Use final and/or comment conventions (see the @modifies and @values tags) to indicate whether instance fields, local fields and argument fields that never have their values changed after construction are intended to be constant (immutable) for the lifetime of the object (as opposed to those that just happen not to get assigned in a class, but could in a subclass).
Rationale: Access to immutable instance fields generally does not require any synchronization control, but access to mutable fields generally does.

Generally prefer protected to private.
Rationale: Unless you have good reason for sealing-in a particular strategy for using a field or method, you might as well plan for change via subclassing. On the other hand, this almost always entails more work. Basing other code in a base class around protected fields and methods is harder, since you have to either loosen or check assumptions about their properties. (Note that in Java, protected methods are also accessible from unrelated classes in the same package. There is hardly ever any reason to exploit this, though.)

Avoid unnecessary public instance field access and update methods. Write public get/set-style methods only when they are intrinsic aspects of functionality.
Rationale: Most instance fields in most classes must maintain values that are dependent on those of other instance fields. Allowing them to be read or written in isolation makes it harder to ensure that consistent sets of values are always used.

Minimize direct internal access to instance fields inside methods. Use protected access and update methods instead (or sometimes public ones if they exist anyway).
Rationale: While inconvenient and sometimes overkill, this allows you to vary synchronization and notification policies associated with field access and change in the class and/or its subclasses, which is otherwise a serious impediment to extensiblity in concurrent OO programming.

Avoid giving a field the same name as one in a superclass.
Rationale: This is usually an error. If not, there must be a very good reason, which should always be explained (in a @hides tag).

Declare arrays as Type[] arrayName rather than Type arrayName[].
Rationale: The second form exists solely for incorrigible C programmers, and makes code less easily readable.

Ensure that non-private static fields have sensible values, and that non-private static methods can be executed sensibly, even if no instances are ever created. Use static intitializers (static { ... } ) if necessary.
Rationale: You cannot assume that non-private statics will be accessed only after instances are constructed.

Write methods that only do "one thing". In particular, separate out methods that change object state from those that just rely upon it. A classic example: in a Stack class, prefer having two methods Object top() and void removeTop() to having the single method Object pop() that does both.
Rationale: This simplifies (sometimes, makes even possible) concurrency control and subclass-based extensions.

Define return types as void unless they return results that are not (easily) accessible otherwise. (i.e., refrain from ever writing "return this;").
Rationale: While convenient, the resulting method cascades (a.meth1().meth2().meth3()) can be sources of synchronization problems and other failed expectations about the states of target objects.

Avoid overloading methods on argument type (overriding on arity is OK, as in having a one-argument version versus a two-argument version). If you need to specialize behavior according to the class of an argument, consider instead choosing a general type for the nominal argument type (often Object, Serializable or Cloneable) and using conditionals which check instanceof (or, reflectively, isAssignableFrom()). Alternatives include techniques such as double-dispatching or, often best, reformulating methods (and/or their arguments) to remove dependence on exact argument type.
Rationale: Java method resolution is static, based on the listed types rather than the actual argument types. This is compounded in the case of non-Object types with coercion charts. In both cases, most programmers have not committed the matching rules to memory. The results can be counterintuitive; thus the source of subtle errors. For example, try to predict the output of this. Then compile and run.
     

class Classifier
{
    String identify( Object x )
    {
        return "object";
    }
    String identify( Integer x )
    {
        return "integer";
    }
}

class Relay
{
    String relay( Object obj )
    { 
        return (new Classifier()).identify( obj );
    }
}

public class App
{
    public static void main( String [] args )
    {
        Relay relayer = new Relay();
        Integer i = new Integer( 17 );
        System.out.println(relayer.relay( i ));
    }
}
    

Declare @concurrency values for all public methods. Describe the assumed invocation context and/or rationale for existence or lack of synchronization. If you don't know the concurrency semantics of your method, make it synchronized.
Rationale: In the absence of planning out a set of concurrency control policies, declaring methods as synchronized at least guarantees safety (though not necessarily liveness) in concurrent contexts (every Java program is concurrent to at least some minimal extent). With full synchronization of all methods, the methods may lock up, but the object can never enter into randomly inconsistent states (and thus engage in stupidly or even dangerously wrong behavior) due to concurrency conflicts. If you are worried about efficiency problems due to synchronization, learn enough about concurrent OO programming to plan out more efficient and/or less deadlock-prone policies (i.e., read "Concurrent Programming in Java" by Doug Lea).

If you override Object.equals(), also override Object.hashCode(), and vice-versa.
Rationale: Essentially all containers and other utilities that group or compare objects in ways depending on equality rely on hashcodes to indicate possible equality. For further guidance see Taligent's Java Cookbook

Override readObject() and writeObject() if a Serializable class relies on any state that could differ across processes, including, in particular, hashCodes and transient fields.
Rationale: Otherwise, objects of the class will not transport properly.

If you think that clone() may be called in a class you write, then explicitly define it (and declare the class to implement Cloneable).
Rationale: The default shallow-copy version of clone() might not do what you want (and, in fact, does not in most cases).

Always document the fact that a method invokes wait().
Rationale: Clients may need to take special actions to avoid nested monitor calls.

Initialize all (reasonable) fields in all constructors, or do not initialize any fields in any constructors (rely on explicit or implicit initialization in field declarations) and always explicitly call the superclass constructor.
If you don't initialize it, you don't know what value it really holds. Consistency is the key in this rule so that a reviewer/user/tool doesn't have to search around for every initialization.

Whenever reasonable, define a default (no-argument) constructor so objects can be created via Class.newInstance().
Rationale: This allows classes of types unknown at compile time to be dynamically loaded and instantiated (as is done for example when loading unknown Applets from html pages). In Java 1.1 and later, reflection alleviates the need for no-argument constructors somewhat, but many classes which dynamically instantiate other classes at runtime still depend on their presence.

Prefer abstract methods in base classes to those with default no-op implementations. Also, if there is a common default implementation, consider instead writing it as a protected method so that subclass authors can just write a one-line implementation to call the default.
Rationale: The Java compiler will force subclass authors to implement abstract methods, avoiding problems which occur when they forget to do so but should have.

Always use method equals instead of operator == when comparing objects. In particular, do not use == to compare Strings.
Rationale: If someone defined an equals method to compare objects, then they want you to use it. Otherwise, the default implementation of Object.equals() is just to use ==.

Never use suspend()/resume() pairs to implement synchronization with threads.
Rationale: The suspend() and resume() are inherently fragile, and have even been deprecated by JavaSoft as of JDK 1.2.

Always embed wait() calls in while loops which re-wait if the condition being waited for does not hold.
Rationale: When a wait() wakes up, there is no guarantee that the condition it is waiting for has become true.

Use notifyAll() instead of notify().
Rationale: Classes that use only notify() can normally only support at most one kind of wait condition across all methods in the class and all possible subclasses.

Declare a local variable only at that point in the code where you know what its initial value should be.
Rationale: Minimizes bad assumptions about values of variables. Of course, you should know about the initial value of most local variables at the beginning of the method. Only one-off (temporary, loop, etc.) variables should be declared within the body of a method.

Declare and initialize a new local variable rather than reusing (reassigning) an existing one whose value happens to no longer be used at that program point.
Rationale: Minimizes bad assumptions about values of variables.

Assign null to any reference variable which is no longer being used. This includes, especially, elements of arrays.
Rationale: Enables the Java garbage collector to do its job.

Avoid assignments ("=") inside if and while conditions.
Rationale: These are almost always typos. The Java compiler catches cases where "=" should have been "==", except when the variable is a boolean.

Document cases where the return value of a called method is ignored.
Rationale: These are usually errors. If it is intentional, make the intent clear. A simple way to do this is: int unused = obj.methodReturningInt (args);

Ensure that there is ultimately a catch for all unchecked exceptions that can be dealt with.
Rationale: Java allows you to not bother declaring or catching some common easily-handlable exceptions, for example java.util.NoSuchElementException. Declare and catch them anyway. It'll make your code more robust.

Embed casts in conditionals. For example:

  C cx = null;
  if ( x instanceof C )
  {
      cx = (C) x;
  }
  else 
  {
      evasiveAction();
  }

Rationale: This forces you to consider what to do if the object is not an instance of the intended class, rather than just generating a ClassCastException.

Document fragile constructions used solely for the sake of optimization.
Rationale: See Jonathan Hardwick's Java Optimization pages.

Do not require 100% conformance to rules of thumb such as the ones listed here!
Rationale: Java allows you program in ways that do not conform to these rules for good reason. Sometimes they provide the only reasonable ways to implement things. And some of these rules make programs less efficient than they might otherwise be, so they are meant to be conscientiously broken when performance is an issue.

Tools

Ant

All our projects are build by Ant

You'll find a distribution in the Distribution Section of the Otego Intranet site.

Emacs

The canonical summary: Emacs is the extensible, customizable, self-documenting real-time display editor.

(Rewritten from the XEmacs home page) Emacs is a powerful, extensible text editor with full GUI and terminal support.

Two primary supported free implementations of Emacs exist:

Extending Emacs. (X)Emacs is extended through the use of Emacs LISP packages. The primary packages we use for the development of Java are as follows (this list is by no means complete and reflects our personal biases):

References

These guidelines are based on example coding standards from several sources including, but not limited to: