Revision: 1.5
Date: 2002/11/01
Latest Version: http://spacemapper.sf.net/mn8/developers/cstandards.html
Editor: Remus Pereni <remus@nolimits.ro>

Back to > Overview > Developers Guide

SpaceMapper Coding Standard

Table of Contents
1. Introduction and Contents
    1.1. Introduction
    1.2. Contents
2. Structure and Documentation
    2.1. Packages
    2.2. Program Files
    2.3. Classes and Interfaces
    2.4. Class Variables
    2.5. Methods
    2.6. Local declarations, statements, and expressions
    2.7. Layout
    2.8. Blank Spaces
    2.9. Wrapping Lines
3. Naming Conventions
4. Recommendations
    4.1. Classes
    4.2. Variables
    4.3. Methods
    4.4. Technical points
    4.5. Common Sense
5. Code Examples
    5.1. Example.java
    5.2. package.html
6. Related Documents


Note: Every Open Source project has to adopt some kind of coding convention in order to reduce the inherent chaos introduced by the high number of developers involved during the life of such an project. In this idea, we choose to adopt the code conventions developed by the Exolab team. The original document, from which this one was adapted, can be found at: http://castor.exolab.org/ExolabJavaConventions.pdf. All the credits for the original version should go to: Arnaud Blandin, Assaf Arkin, Keith Visco and the Exolab Team.

Before complaining about this document, please read the following:

Whenever possible, use the conventions from this document; do not reinvent them. Keep in mind that projects (whether it is a software project or not) are not developed in a vacuum and organizations do not work in a vacuum either.

A standard is never perfect and can not fit all situations: it is be possible that one day you find yourself in a situation where none of these conventions could be applied. Thus, you might want to break the conventions to fit your particular situation; if you do so, document it. If you go against a standard, you must document why you broke it and the potential implications of breaking it.

The bottom line is that you need to understand each standard and understand fully when to apply it (and also when not to apply it).

To conclude please note that some parts of this document are freely adapted or quoted from Doug Lea's Java Coding Standard.

1. Introduction and Contents

1.1. Introduction

Code conventions are important to programmers for a number of reasons:

top

1.2. Contents

Structure and Documentation
Standard ways to write and document constructions
Naming conventions
Standard ways to name identifiers (class names, method names, variable names, etc).
Recommendations

Some rules of thumb that tend to avoid common errors and development obstacles. You can use these guidelines to make your own design and coding checklists to be used in retrospective code clean-up or when classes need to be used in new contexts or placed in reusable libraries. But please do not forget to follow the last one.

Code Examples
'Example.java' uses the code conventions of this document. 'Package.html' outlines the purpose of a package.
Related Documents
References to other style guidelines etc.
top

2. Structure and Documentation

2.1. Packages

Create a new java package for each self-contained project or group of related functionality. Create and use directories in accord with java package conventions. Consider writing a package.html file in each directory briefly outlining the purpose and structure of the package.

top

2.2. Program Files

Place each 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. Begin each file with a comment including:

  1. The copyright. (http://www.exolab.org/license.html)
  2. The '$Id: cstandards.xml,v 1.5 2002/11/01 02:30:11 neuro Exp $' tag
  3. A history table listing dates, authors, and summaries of changes.
  4. If the file contains more than one class, list the classes, along with a very brief description of each.
  5. If the file introduces a principal entry point for a package, briefly describe the rationale for constructing the package.

Immediately follow each file header with:

          

Example: /** * Redistribution and use of this software and associated * documentation * ("Software"), with or without modification, are permitted provided * that the following conditions are met: * * 1. Redistributions of source code must retain copyright * statements and notices. Redistributions must also contain a * copy of this document. * * 2. Redistributions in binary form must reproduce the * above copyright notice, this list of conditions and the * following disclaimer in the documentation and/or other * materials provided with the distribution. * * 3. The name "Exolab" must not be used to endorse or promote * products derived from this Software without prior written * permission of Exoffice Technologies. For written permission, * please contact info@exolab.org. * * 4. Products derived from this Software may not be called "Exolab" * nor may "Exolab" appear in their names without prior written * permission of Exoffice Technologies. Exolab is a registered * trademark of Exoffice Technologies. * * 5. Due credit should be given to the Exolab Project * (http://www.exolab.org/). * * THIS SOFTWARE IS PROVIDED BY EXOFFICE TECHNOLOGIES AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT * NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL * EXOFFICE TECHNOLOGIES OR ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * * Copyright 1999 (C) Exoffice Technologies Inc. All Rights Reserved. * $Id: cstandards.xml,v 1.5 2002/11/01 02:30:11 neuro Exp $ * Date Author Changes * Aug 2 2000 author-name Created * Aug 2 2000 author-name Added new methods */ package demo; import java.util.NoSuchElementException;

top

2.3. Classes and Interfaces

Write all /** ... */ comments using javadoc conventions.
Preface each class with a /** ... */ comment describing the purpose of the class, guaranteed invariants, usage instructions, and/or usage examples. Also include any reminders or disclaimers about required or desired improvements. Use HTML format, with added tags:


            Example: 
            /**
            * A class representing a window on the screen.
            * For example:
            * <pre>
            *   Window win = new Window(parent);
            * win.show();
            * </pre>
            *
            * 
            * @author <link href="mailto:clown@exolab.org">Bozo the Clown</link>
            * @version $Revision: 1.5 $ $Date: 2002/11/01 02:30:11 $
            * @see    awt.BaseWindow
            * @see    awt.Button
            */
            class Window extends BaseWindow {
            ...
            }

          

Declaration order:

top

2.4. Class Variables

First declare public variables, then protected ones , then package level ones and then the private ones.

Use javadoc conventions to describe nature, purpose, constraints, and usage of instances variables and static variables. Use HTML format, with added tags:

            Example: 
            /**
            * The current number of elements.
            * must be non-negative, and less than or equal to capacity.
            */
            protected int _count;
          

top

2.5. Methods

Use javadoc conventions to describe nature, purpose, preconditions, effects, algorithmic notes, usage instructions, reminders, etc. Use HTML format, with added tags:

Be as precise as reasonably possible in documenting effects.

top

2.6. Local declarations, statements, and expressions

Use /* ... */ comments to describe algorithmic details, notes, and related documentation that spans more than a few code statements. You can also use // (see below). Do not forget to document why something is being done, not just what. With some time every one can figure out what your code is doing but can hardly say why you choose to do that.

          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. But don't bother adding such comments to obvious code; instead try to make code obvious!

          Example: 
          int index = -1; // -1 serves as flag meaning the index isn't valid
          Or, often better: 
          static final int INVALID = -1; 
          int index = INVALID;
        
top

2.7. Layout


          Examples:
          class Example1
          extends Class1,Class2,Class3,Class4,Class5
          {
          if (condition) {
          ...
          } else {
          ...
          }
          } //--Example1
          
          class Example2 extends Class1 {
          
          ...
          if (condition) {
          ...
          }
          
          else {
          ...
          }
          
          } //--Example2

        

top

2.8. Blank Spaces

Blank spaces should be used in the following circumstances:

top

2.9. Wrapping Lines

When an expression does not fit on a single line, break it in order to make your code as readable as possible.

Here are some simple principles you can follow:

          Examples:
          SomeMethod(longExpression1,longExpression2,
          longExpression3, longExpression4,
          longExpression5);
          
          var = someMethod1(longExpression1,
          someMethod2(longExpression2,
          longExpression3));
        

Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.

          longName1 = longName2 * (longName3 + longName4 - longName5)
          + 4 * longname6; // PREFER
          longName1 = longName2 * (longName3 + longName4
          - longName5) + 4 * longname6; //AVOID 
        
top

3. Naming Conventions

packages
lowercase Consider using the recommended domain-based conventions described in the Java Language Specification, page 107 as prefixes.
files
The java compiler enforces the convention that file names have the same base name as the public class they define.
classes
CapitalizedWithInternalWordsAlsoCapitalized
class
(When necessary to distinguish from similarly named interfaces): ClassNameEndsWithImpl OR
ClassNameEndsWithObject
exception class
ClassNameEndsWithException.
constants (finals)
UPPERCASE_WITH_UNDERSCORE_IF_MORE_THAN_ONE_WORD
private or protected
_firstWordLowerCaseWithUnderscoreAndInternalWordsCapitalized
local variables
firstWordLowerCaseButInternalWordsCapitalized
methods
firstWordLowerCaseButInternalWordsCapitalized()
factory method for objects of type X:
newX OR
createX
converter method that returns objects of type X
toX
method that reports an attribute x of type X
X getX()
method that changes an attribute x of type X
void setX(X value)
top

4. Recommendations

4.1. Classes

top

4.2. Variables

top

4.3. Methods

top

4.4. Technical points

top

4.5. Common Sense

top

5. Code Examples

5.1. Example.java

          /**
          * Copyright 2000  Exolab Group Inc. All Rights Reserved
          * $Id: cstandards.xml,v 1.5 2002/11/01 02:30:11 neuro Exp $
          * File: Example.java
          * Date       Author         Changes
          * Aug 2 2000 author-name    Created  
          * Aug 2 2000 author-name    Added new classes
          */
          package com.intalio.n3.xml;
          import java.io.Serializable;
          import java.net.URL;
          import java.net.MalformedURLException;
          /**
          *Hold the URI reference and reference the base URI 
          *or the namespace in which the URI is defined. It 
          *allows URI references to be passed between application 
          *components as well as encoded into XML documents.
          *
          *@author <a href=e-mail address> author name </a>
          *@version $Revision: 1.5 $
          *@see URNNamespace
          */
          public class URIReference implements Serializable{
          /**
          * Holds the identifier for this URI
          */
          private String _identifier;
          /**
          * the URI reference to which this reference is relative
          */
          private URIReference _baseURI;
          /**
          * The URNNamespace for this URI
          *
          *@see URNNamespace
          */
          private URNNamespace _namespace;
          /**
          * Constructs a new URI reference from the given URL
          *
          * @param url The URL
          */
          public URIReference(String url) {
          _identifier = url;
          }
          
          /**
          * Returns the resource identifier as a string. The return
          * Is either the URL (absolute or relative) or the URN   
          * identifier (namespace specific string). 
          *
          * @return The resource identifier as a string
          */
          public String getIdentifier() { 
          return _identifier;
          }
          /**
          * Returns true if both URI references are equal.
          * Two URI references are equals if they have the same
          * identifier, the base URI is null or equal, and the
          * URN namespace is null or equal
          */
          public boolean equals(Object other) {
          ...
          
          while (condition) {
          ...
          }
          do {
          ...
          } while (condition);
          } //equals
          public int hashCode() {
          ...
          switch (condition) {
          case ABC:
          if (condition) {
          ...
          } else {
          ...
          }
          break;
          case DEF:
          for (initialization; condition; update) {
          statements;
          }
          break;
          case XYZ:
          {
          ...
          }
          break;
          default:
          statements;
          break;
          } //switch
          try {
          statements;
          } catch (ExceptionClass e) {
          statements;
          } finally {
          statements;
          }
          }//hashCode
          }//-- Example
        
top

5.2. package.html

          <html>
            <body>
              <p><b>The Java Data Objects API</b></p>
              <dl>
                <dt><b>Version: </b></dt><dd>$Revision: 1.5 $ $Date: 
                  2000/05/13 00:45:01 $</dd>
                <dt><b>Author:</b></dt>     
                <dd><a href="mailto:arkin@exoffice.com">  
                    Assaf Arkin</a></dd>
              </dl>
              <p>The class {@link org.exolab.castor.jdo.JDO}    
                provides the Castor JDO engine used for obtaining
                database connection. A JDO object is constructed with the
                name of a database and other properties, and <tt>
                  getDatabase}</tt> is used to obtain a new database connection.</p>
              <p>The class {@link org.exolab.castor.jdo.Database}   
                represents an open connection to the database that 
                can be used to perform transactional operations on 
                the database.</p>
              <p>Database operations can only be performed in the    
                context of a transaction. Client  applications    
                should begin and commit a transaction  using the  
                <tt>begin</tt> and <tt>commit</tt> methods. Server     
                applications should use implicit transaction demarcation  
                by the container or explicit transaction demarcation  
                using <tt>javax.transaction.UserTransaction</tt>.</p>
              <p>All objects queried and created during a transaction    
                are persistent. Changes to persistent
                objects will be stored in the database when the  
                transaction commits. Changes will not be
                stored if the transaction is rolled back or fails to   
                commit.</p>
              <p>The class {@link org.exolab.castor.jdo.OQLQuery} is    
                obtained from the database and used to
                construct and execute a query on that database. All  
                query operations are bound to the database
                transaction.</p>
              <p>The following example opens a connection to the 
                database 'mydb' configured from the
                configuration file '<tt>database.xml</tt>', retrieves  
                all the products in the specified
                groups and marks them down with a 25% discount and on-   
                sale status.</p>
              <pre>
                JDO          jdo;
                Database     db;
                Query        oql;
                QueryResults results;
                <font color="red">// Define a new database source</font>
                jdo = new JDO( "mydb" );
                jdo.setConfiguration( "database.xml" );
                <font color="red">// Open a new database, begin a transaction</font>
                db = jdo.getDatabase();
                db.begin();
                <font color="red">// Select all the products in a given group</font>
                oql = db.getQuery( "SELECT p FROM Product p WHERE group=$" );
                oql.bind( groupId );
                results = oql.execute();
                while ( results.hasMore() ) {
                <font color="red">// A 25% mark down for each    product and mark as sale</font>
                prod = (Product) results.next();
                prod.markDown( 0.25 );
                prod.setOnSale( true );
                }
                <font color="red">// Commit all changes, close the database</font>
                db.commit();
                db.close();
              </pre>
            </body>
          </html>
        
top

6. Related Documents

For some others standards and style guides, see:

top


© 2001