CCL Java Coding Standard


Table of Contents

0 Introduction
1 Project Organization
  1.1 The Main Class and main Method
  1.2 The Special $package Interface
2 File Structure
  2.1 License Comment
  2.2 Package Statement
  2.3 Import Statements
  2.4 Class/Interface Comment
  2.5 Blank Lines
3 Formatting Rules
  3.1 Tabs and Indentation
4 Naming Conventions
  4.1 Identifiers
  4.2 Hungarian Notation
5 Links


0 Introduction

This document describes style guidelines for Java source code I'm personally using. I have developed this style over the last 3 1/2 years (it's now 1999-07-10) coding Java and I feel comfortable using it. It is not that I think it is the best style ever possible, it is just what I like but it helps me personally during development.

I think there is no right style. I don't even believe that all team members should be forced to stick to the same style guide. But everyone should have his own consistent style and at least each project file should have a consistent style.

For me, a consistent style helps to write software faster. If other people unfamiliar with my style need longer to read my code it is a tradeoff I am willing to do. I need less thinking when I type, because many details are written by reflexes. I think when I read code (my own or someone else's), the style does not matter that much as long as it is consistent. Of course, some details of my own style help me understand my code much faster like '_' in front of global class variables or '_' at the end of method argument variables etc. and I miss them when I read other peoples code and don't see them. But then there are other ideas how to put extra information in the code that I don't use and other people used to it might miss this in my code.

Anyway, writing source code is a very personal thing, and I believe different styles should reflect different personalities. To force people to use uniformly the same style is communism in my book ;-).

This document is for people who have to or want to read my code and also want explanations about some stylistic details.

The content of this document is basically ripped together from some other Java coding standards and mixed together to my own liking. See the links section for the original works this one is based upon.


1 Project Organization

1.1 The Main Class and main Method

The public static main Routine should be in a Class called Main in the package named the same as the application/project name. This main method should exit with a System.exit( 0 ) method invocation. No other place in the application should invoke exit( 0 ). Of course, there should be very rare situations that a exit( 1 ) makes sense, and it should happen also just in the main method and maybe just for batch mode files when the user gave wrong parameter to the application. Do not exit the application in window listeners.

1.2 The Special $package Interface

For each package there is one special $package interface. Its only purpose is to have a place to put documentation about this package at a well defined place. In this case the documentation will be put in the interface documentation comment. The $ at the beginning is just to make sure, in the javadoc generated html files this interface will be at the top of the interface/classes list. If your package is actually a subpackage, use '_' instead of '.' (for example: $ccl_util).


2 File Structure

2.1 License Comment

A Java source file starts with a c-style comment with the project/file license it will be distributed with. For example:
/*
 * The contents of this file are subject to the Mozilla Public License
 * Version 1.0 (the "License"); you may not use this file except in
 * compliance with the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 * 
 * Software distributed under the License is distributed on an "AS IS"
 * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
 * License for the specific language governing rights and limitations
 * under the License.
 *
 * The Original Code is the reusable ccl library
 * (http://www.kclee.com/clemens/java/ccl/).
 *
 * The Initial Developer of the Original Code is Chr. Clemens Lee.
 * Portions created by Chr. Clemens Lee are Copyright (C) Chr.
 * Clemens Lee. All Rights Reserved.
 * 
 * Contributor(s): Chr. Clemens Lee <clemens@kclee.com>
 */

2.2 Package Statement

The first non-comment line of most Java source files is a package statement. After that, import statements can follow. For example:

      package ccl.util;

The first component of a unique package name is always written in all-lowercase ASCII letters. Personally I don't care for the convention of naming packages after domain names :-).

Package names should use singular words like java.awt.event, jacob.tool, or com.websentric.presto.dialog. 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.

2.3 Import Statements

    import ccl.util.FileUtil;
    import java.awt.Frame;
    import java.awt.event.KeyEvent;

Import statements should be explicit and without statements like

    import java.awt.*;

Such statements make it very hard to read and find classes your source makes references to. Also the imported classes should ordered alphabetically and without empty lines. I don't use empty lines because of my Jacob development tool that inserts import statements automatically for me and expects this sorted order.

2.4 Class/Interface Comment

For example:
/**
 * Example class does this and that ...
 *
 * @author <a href="http://www.kclee.com/clemens/">
 *         Chr. Clemens Lee</a>
 *         &lt;<a href="mailto:clemens@kclee.com">
 *         clemens@kclee.com
 *         </a>>
 * @version $Id: CCLJavaCodingStandard.html,v 1.2 1999/07/15 11:05:08 clemens Exp clemens $
 */
public class Example {
    ...

2.5 Blank Lines

License comment, package statement, import statements group, and class/interface comment are each separate by exactly one blank line. There is no blank line between class/interface comment and the start of the class definition itself.


3 Formatting Rules

3.1 Tabs and Indentation

Tabs are 8 spaces and each indentation level consists of 4 spaces. Tabs should not be used at all if possible. Instead just spaces should be used for indenting.

Rationale:
Tools like less expect a tab setting of 8. If your editor uses a different setting, these tools are next to useless for a quick look at your code. Personally I used an indentation level of 3 for a long time, but with a value of 4 it is better possible to mix tabs and spaces. Nevertheless, if you editor is able to replace every tab with spaces anyway, this saves a lot of trouble, for example when checking in and out of cvs. if only spaces <-> tabs changed, this  irritates diff quite a lot. Also, no matter how other people did set their tabs value in their editor, if only spaces are used, your code looks the same in every editor.

Tabs and indentation depth are one of the few things that should be explicitly specified for a whole team, but not necessarily the same as in this document.


4 Naming Conventions

4.1 Identifiers

Below are conventions and examples for different identifiers. Especially noteworthy are the leading underscores used for private class variables and methods and the trailing underscore used for method parameter variable names.

packages:
      lowercase
classes:
      CapitalizedWithInternalWordsAlsoCapitalized
methods:
      firstWordLowerCaseButInternalWordsCapitalized
      start the method name with a verb
private or protected methods:
      _firstWordLowerCaseButInternalWordsCapitalized
constants (finals):
      UPPER_CASE_WITH_UNDERSCORES
string constants (finals):
      S_UPPER_CASE_WITH_UNDERSCORES
float/double constants (finals):
      F/D_UPPER_CASE_WITH_UNDERSCORES
private or protected class variable:
      _leadingUnderscore
method local variables:
      firstWordLowerCaseButInternalWordsCapitalized
method parameter variable:
      trailingUnderscore_
Exception class:
      ClassNameEndsWithException
Interface. Java interface names end with the suffix "-able" or "-ible"-or (occasionally) "-er.":
      Interfacable, DoSomethingPossible, or Listener

4.2 Hungarian Notation

I use a weak form of Hungarian Notation to name variables. The only methods that have no prefix are ints. For me this is the most common type of variable. So if you see no prefix, it is an int. Sometimes you have a class and one object of this type of class. For example:

   Car car = new Car();

Just like in C I use p as a prefix. In this case: pCar. Other choices would have been, theCar, aCar, or rCar (r for Reference). But I like p for Pointer even thought technically JVM seldom use Pointers to implement References internally.

In the literature and on usenet there a big flame wars going on in favor and agains Hungarian Notation. For me the way I handle it, it helps me a lot to know the type where I see a variable without the need to scroll around to look it up, while still everything is pretty readable (at least for me :-).

Below are some examples.
 

int <no prefix> int index; This is the most common used type and therefore I omit a prefix.
instance of Type pType Timer pTimer; Use this if there is only on variable of this type around, for example when it is clear that it is The Timer.
String s String sName;  
array a String[] asName = new String[ 11 ];  
boolean b boolean bError;  
Vector v Vector vArgs; When the type of the objects contained in this vector are know, a more specific prefix can be used, like vs etc.
Enumeration e Enumeration eSelection;  
Object o Object oNextElement;  
Integer i Integer iLength;  
Hashtable ht Hashtable htProperties;  
Thread thr Thread thrAWT;  
Exception exc Exception excRead; Most of the time I use 'Exception pException;'.
Frame, JFrame frm Frame frmParent; We use the same prefixes for awt and swing objects. Normally they are not mixed anyway and except for some base classes we use only swing classes nowadays.
Dialog, JDialog dlg JDialog dlgMessage;  
Window, JWindow win JWindow winSplash; I know it is not consequent not to use 'wnd' instead of 'win'.
Dimension dim Dimension dimScreen; The same as above.
Label, JLabel lbl JLabel lblHeadline;  
List, JList lst JList lstAnniversaries;  
Button, JButton btn JButton btnOK;  
TextField, JTextField, JTextArea, JTextPane, etc. txt JTextArea txtComment; I use for all different kind of text objects the same prefix. Did not have a problem yet confusing their types.


5 Links


Chr. Clemens Lee <clemens@kclee.com>, first released: 1999-07-15, last modified: $Date: 1999/07/15 11:05:08 $