
marc.meurrens@acm.org
(
http://homepages.ulb.ac.be/~meurrens)
sja@bejug.org)
will not be published here.
http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/index.html
[back]
"FICS Java Coding Standards"
FICS together with a compilation of usefull rules gathered from various sources; we decided to remove the internal FICS recommandations from the (not publicly available) original document. For more details, contact
sja@bejug.org
FICS Java Coding Standards
Created by:
Stephan Janssen
Date: 9 May 1997
Version : 1.33

1. Introduction
2.1. Comments
2.1.1. Packages
2.1.2. Program Files
2.1.3. Classes & Methods
2.1.4. Class variables, Local declarations, statements and expressions
2.2. Control structures
2.3. Visual layout
2.3.1. Spacing Around Operators
2.3.2. Indentation and Braces
3.1. Packages
This section is partially removed in this mirror
3.2. Files
3.3. Classes
3.4. Interfaces
3.5. Exceptions
3.6. Constants (finals)
3.7. Methods
3.8. Variables
5.1. Debug Switch
6.1. Using MKS (command line interface)
This section is removed in this mirror
This document contains guidelines for Java coding. These guidelines are not to restrict your programming innovation, but rather to impose a consistent format for our Java programs.
The biggest gains we get by conforming to any coding styles are :
This document is a compilation of existing C++ /
Java standard documents that can be found on the net, please refer to the
"Related documents" for more information.

Comments can be divided into two general categories, strategic and tactical.
Strategic comments are used to give the reader a general overview of what is going on. These comments appear at the top of the files and before the function code. Strategic comments tend to be written in a prose style.
Tactical comments are designed to explain tricky areas of code, what parameters do, and hints about the control flow of the program. These comments are imbedded in the code and tend to be shorter and in bullet format.
The javadoc will be used to develop documentation files.
NOTE : Use arguments -version and -author with the javadoc utility to include these tags in your information header.
If you use proper naming, block structure, indentation, and straight forward programming, your code will be mostly self documenting. This is what you should strive for.
Use the Java (C++) "/*"......"*/" or "/**" …… "*/" construct for all comments. This will allow you to block out sections of code with the old comments and allows you to generate html specific code documents, but this is not necessary in all cases. Please note that this is not applicable for tactical comments !
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. (see Naming Conventions for more detailed information on packages)
Consider writing an index.html file in each directory briefly outlining the purpose and structure of the package.
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:
Immediately follow each file header with:
Example:
/**
* $Date$
* $Author$
* $Header$
* $Name$
* $ProjectName$
* File: _________________
* © 1997, FICS Group NV/SA
* Operating Environment: ________________ (optional)
* Compiler: _____________________ (optional)
* Description: _________________________
* Algorithm: (Give a step-by-step alogorithm)
*
* To Do : blablablabla all is done :-)
*
* History :
*
* Date
Author
Comments
* -------------------------------------------------------------------------------------------------------------
* 30 May 1997 Stephan
Janssen First release
*
*/
Each class source file shall terminate with an end
of file comment of the form:
//end of file test.java
Each class, method declaration must have a description in comments preceding it. The declaration will contain a comment pertaining to usage, and the definition should contain comments relating to the implementation.
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. Here are some conventions and practices for semi-formal specifications.
@return condition: (condition)
describes postconditions and effects true upon return of a method.
@exception exceptionName IF (condition)
indicates the conditions under which each exception can be thrown. Include conditions under which uncommon unchecked (undeclared) exceptions can be thrown.
@param paramname WHERE (condition)
indicates restrictions on argument values. Alternatively, if so implemented, list restrictions alongside the resulting exceptions, for example IllegalArgumentException. In particular, indicate whether reference arguments are allowed to be null.
Before you start coding your class, put
general information above the class declaration (such as author,
version and other class relations).
See below for example :
/**
* This class handles counters
* @author Stephan Janssen
* @version 1.2 30 May 97
* @see java.lang.date
*/
public class counter {
/**
* This method takes a counter and converts it to the lapsed
time
* @return time - time corresponding to program counter
* @param count - the current program count value
*/
public int countTime(int count) {
int time = count * 2;
return time;
}
}
// end of counter.java
Use /* ... */ comments to describe algorithmic details, notes,
and related documentation that 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. 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;
To make java sources more readable we'll give you some
recommendations on java source layout.
This layout will be automatically inforced by a formatting
program that will be triggered whenever you call the makefile script.
Spacing around operators and delimiters should be consistent. In general, insert one space before or after each operator to improve readability. Use spaces inside of the parentheses around the argument list. Do not use a space within empty argument lists () or non-dimensioned arrays [].
Do not use spaces around the member access operators (.
= space)
if.(.value.==.0.).{ // right
if.(value==0){
// not recommended
void doIt(.int.v.); // right
void doIt(int.v); // not recommended
The contents of all code blocks should be indented to improve readability. A single tab or four spaces are recommended as the standard indentation. Braces should be placed to show the level of indentation of the code block, with the open brace at the end of the statement which starts the block, and the close brace indented to match the statement.
void getValue() {
if ( value == 0 ) {
doSomething();
} else if ( value == 2 ) { // note position of cascaded if
statement
doSomething2();
} else {
doSomething3();
}
while ( value < 300 ) {
doSomething();
}
do {
doSomething();
} while ( value < 300 ) // note: ending brace and control on same line
switch ( value ) {
case 1: doSomething();
break;
case 2:
case 3: doSomething2();
break;
default: break; // final break required
}
The location of the packages in the Symantec project files needs to be a relative directory ! We must avoid hard coded settings in the projects files and this to help cross environment / multi-user developing.
uppercase : FICS
lowercase
See the package-based conventions described below :
This section is partially removed in this mirror

The java compiler enforces the convention that file names
have the same base name as the public class they define.
FirstWordUpperCaseButInternalWordsCapitalized
When necessary to distinguish from similarly named interfaces:
ClassNameEndsWithImpl (this is used when implementing a Interface !)
or ClassNameEndsWithObject
When necessary to distinguish from similarly named classes:
FirstWordUpperCaseButInternalWordsCapitalized
The implementation of this interface ends with Impl !
classNameEndsWithException
UPPER_CASE_WITH_UNDERSCORES
firstWordLowerCaseButInternalWordsCapitalized()
firstWordLowerCaseButInternalWordsCapitalized
Exceptions are for changing the flow of control when some important or unexpected event, usually an error, has occured. The divert processing to a part of the program that can try to cope with the error, or at least die gracefully. The error can be any condition at all, ranging from "unable to open a file" to "array subscript out of range" to "division by zero".
Java allows you to not bother declaring or catching some
common easily-handlable exceptions, for example java.util.NoSuchElementException.
We'll NOT CATCH the unchecked exceptions !

Code used only during development for debugging or performance
monitoring should be conditionally
compiled using specific compile-time switches. The symbols
to use are #DEBUG and #END respectively.
Debug statements announcing entry into a function or member
function should provide the entire function name including the class. For
example:
// #DEBUG
Debug.debug("ODM", "ODM::Events: Keyboard
error: press F1 to continue J ");
// #ENDDEBUG
As Java does not support preprocessing we'll simulate this functionality by using a sed script that will
comment or uncomment the lines between #DEBUG / #END when executed !
This section is removed within this mirror
This list gives you general recommendations on Java programming.
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.
Rationale: Forms a basis for testing. Also provides usage examples.
Rationale: Hard-wiring an application program in one of its component class files hinders reuse.
Rationale: Simplifies conformance to coding standards.
Rationale: Interfaces are more flexible than abstract classes. They support multiple inheritance and can be used as `mixins' in otherwise unrelated classes.
Rationale: These are ``magic'' interfaces in Java, that automatically add possibly-needed functionality only if so requested.
Rationale: Making a class final means that no one ever has a chance to reimplement 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.
Rationale: The standard OO reasons. Making variables public gives up control over internal class structure. Also, methods cannot assume that variables have valid values.
Rationale: Minimizes initialization
errors.
Rationale: Static variables 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 variables nor methods are overridable in any useful sense in subclasses.
Rationale: Arithmetic overflow and underflow can be 4 billion times less likely with longs than ints; similarly, fewer precision problems occur with doubles than floats. On the other hand, because of limitations in Java atomicity guarantees, use of longs and doubles must be synchronized in cases where use of ints and floats sometimes would not be.
Rationale: Access to immutable instance variables generally does not require any synchronization control, but others generally do.
Rationale: Unless you have good reason for sealing-in a particular strategy for using a variable 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 variables and methods is harder, since you 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 every any reason to exploit this though.)
Rationale: Most instance variables in most classes must maintain values that are dependent on those of other instance variables. Allowing them to be read or written in isolation makes it harder to ensure that consistent sets of values are always used.
Rationale: While inconvenient and sometimes overkill, this allows you to vary synchronization and notification policies associated with variable access and change in the class and/or its subclasses, which is otherwise a serious impediment to extensiblity in concurrent OO programming. (Note: The underscore convention for instance variables serves as an annoying reminder of such issues.)
Rationale: This is usually an error. If not, explain the intent.
Rationale: The compiler will not see this as an error but can cause misinterpretation.
Rationale: The second form is just for incorrigible C prgrammers.
Rationale: You cannot assume that non-private statics will be accessed only after instances are constructed.
Rationale: This simplifies (sometimes, makes even possible) concurrency control and subclass-based extensions.
Rationale: While convenient, the resulting method cascades (a.meth1().meth2().meth3()) can be the sources of synchronization problems and other failed expectations about the states of target objects.
Rationale: Java method resolution is static; based on the listed types, not the actual types of argument. 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));
}
}
Rationale: In the absence of planning out a set of concurrency control policies, 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 in randomly inconsistent states (and thus engage in stupidly or even dangerously wrong behaviors) due to concurrency conflicts.
Rationale: Better encsapsulation; less prone to subclassing snags; can be more efficient.
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
Rationale: Otherwise, objects of the class will not transport properly.
Rationale: The default shallow-copy version of clone might not do what you want.
Rationale: Clients may need to take special actions to avoid nested monitor calls.
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).
Rationale: The Java compiler will force subclass authors to implement abstract methods, avoiding problems occurring when they forget to do so but should have.
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 ==.
Rationale: When a wait wakes up, it does not know if the condition it is waiting for is true or not.
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. And unguarded suspends/resumes are even more fragile.
Rationale: Minimizes bad assumptions about values of variables.
Rationale: Minimizes bad assumptions about values of variables.
Rationale: Enables garbage collection.
Rationale: There are almost always typos. The java compiler catches cases where ``='' should have been ``=='' except when the variable is a boolean.
Rationale: These are typically errors. If it is by intention, make the intent clear. A simple way to do this is: int unused = obj.methodReturningInt(args);
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.
Rationale: See Jonathan Hardwick's Java Optimization pages.
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 are meant to be concientiously broken when performance is an issue.
For some other standards and style guides, see :
Draft
Java Coding Standard by Doug Lea.(mirrored
here)
Coding
Standards for C, C++, and Java by Vision 2000 CCS Package and Application
Team.(mirrored
here)
Naval
Postgraduate School Java Style Guide.
(mirrored
here)
|
Brussels July 8, 1997
mirror of internal work dated "May 9, 1997 - version 1.33" by Stephan Janssen ( sja@bejug.org)
published by marc.meurrens@acm.org
( http://homepages.ulb.ac.be/~meurrens)
original URL: $source-URL$
current URL: http://www.ulb.ac.be/esp/ip-Links/Java/joodcs/Stephan.html
internet programming Links: http://www.ulb.ac.be/esp/ip-Links (ip-Links)
Université Libre de Bruxelles: http://www.ulb.ac.be (ULB)
La Cambre - Architecture: http://www.lacambre-archi.be
Belgian JAVA User Group: http://www.bejug.org (BeJUG)
| |||||||||||||||||
|
Use this form to send your feedback and/or submit a link
| |||||||||||||||||
Conventions used in these pages:
html file, text file or java or CPP source located on our site
download area (on our site) or file to be downloaded (use the right button of your mouse)
document on a belgian academic or scientific site
document (on another site) or link to be fixed or link we didn't visit/evaluate; documents indicated with their full URL will be displayed in their own "top" window.
ftp download or
file to be downloaded (use the right button of your mouse)
indicates a "mailto" link.
Click on the | |||||||||||||||||
| |||||||||||||||||