Coding Standard for Java
1. Content
1. Content ___________________________________________________________________ 1 2. Introduction _______________________________________________________________ 1 3. Naming convention for Files/Packages _________________________________________ 1 4. Naming convention for Classes, Interfaces, Members and Variables ________________ 2 5. File Layout (.java) __________________________________________________________ 3 6. Comment Conventions ______________________________________________________ 4 7. Variable Comments_________________________________________________________ 6 8. Inline Comments ___________________________________________________________ 7 9. Referenced Documents ______________________________________________________ 7
2. Introduction
The Consistent and descriptive naming of files, packages, classes, variables and members is the most effective way to produce readable code in any language. The naming conventions in this section specify the use of mixed case and underscores. Convention 1 carries over to all naming conventions specified in this section.
Convention 1 - All names will be English words. The name shall be descriptive and unambiguous.
The name of a method or class should go a long way towards describing what it does. Avoid using abbreviations, acronyms and computer jargon unless it is extremely awkward not to do so.
Convention 2 – Code traditions force a split in the practices for acronym capitalization. In C++
capitalize only the first letter of an acronym (ie. calculateCrcValue() ). In Java capitalize all letters of an acronym (ie. calculateCRCValue() ).
Convention 3 – Do not rely on capitalization to discriminate between classes, structs or files even if the compiler permits it.
3. Naming convention for Files/Packages
The file name will match the class name that it contains. Capitalizing package names identify user packages from Java standard packages.
Convention 1.1 – A file is named after the class or class implementation that it contains. A file that does not contain a class will be named according to what it contains.
Convention 1.2 – File and package names begin with a capital letter followed by all lower case letters.
Multiple word filenames are all lower case except the first letter of each word. For example:
package SerialLineDriver; (Hardware driver package name) Clock.java (Clock class implementation contained in here)
AnalogToDigitalConverter.java (A/D implementation contained in here)
package MyControlPanel; (my windowing package) Frame.java; (Frame Class implementation contained in here)
InformerButton.java (Informer Button GUI class implementation in here)
4. Naming convention for Classes, Interfaces, Members and Variables Classes and Members must have descriptive name and a consistent scheme for capitalization and underscoring. This helps a reader understand what it is for and whether it will be useful.
Convention 2.1 – The visibility attributes of classes and their members shall be explicitly defined as public, private, private protected or protected.
Convention 2.2 – The default value of each Data member shall be explicitly assigned where the member is declared.
Convention 2.3 – Class, interface, struct, typedef and enumerate type names shall use mixed case to conform to traditional naming conventions. That means the first letter of each word in a name begins with a capital followed by all lower case letters (ie. SerialLineDriver).
Convention 2.4 – Method names will be of mixed case with the first letter in lower case. (ie.
“getValue()” )
Convention 2.5 – Data Member names will be of mixed case with the first letter in lower case beginning with an underscore. Multiple word names shall have the first letter of each word capitalized. (ie. _startTime )
Convention 2.6 – Constants are named with all capital letters. A Java data member declared final static will be named in all capital letters. Multi-word names will be separated by an underscore.
Convention 2.7 – Automatic or local variables and method parameter names will be of mixed case with the first letter in lower case.
Java Naming Example (without comments) public class OneShotTimer
{
public OneShotTimer () {
}
public int setTimeoutInterval(int theTimeoutInterval) {
float secondsToTimeout = 0.0;
secondsToTimeout = theTimeoutInterval / SECONDS_CONVERSION;
_stopTime = _startTime + secondsToTimeout;
}
public final static long SECONDS_CONVERSION = 1000;
private long _stopTime = 0;
}
Convention 2.8 – An enumerate type’s enumeration’s are all capital letters with a prefix identifying the enumerate type. Explicit values should be provided with enumerates.
Enumerate Example
enum ActualServiceType {
AST_NOTYPE = 1, //default state
AST_REGULAR = 2, //service under normal conditions
}
5. File Layout (.java)
Use of a typical file layout significantly improves a developer’s ability to find classes and their implementation details. A consistent indentation and spacing scheme improves readability.
Convention 3.1 – All Java source files (.java) contain one class implementation. The file header comment block starts at the first line, followed by the context clause, class level comments and finally the class implementation.
Convention 3.2 – A class comment block precedes a class declaration. Within a class definition the public constructors are listed first; followed by public methods, protected methods, public data, protected data, private data and then private methods.
Convention 3.3 – Indentation is three spaces. Braces are indented to the same level as the opening statement.
Convention 3.4 – Line Spacing. I.e. closing braces and atomic statements belong on separate lines.
Convention 3.5 – Braces for class- and method-definition belong under the declaration-statement (on a separate line) and the declaration is indented by itself.
Example
import java.io.*;
public class Example1303 {
public static void main(String args[]) {
//Hier steht der Methodenrumpf }
}
Convention 3.6 – Opening Braces for control-statements (within methods) belong to the same line as the introducing statement; this also applies to the else-statement. If the arguments of a method-call have not enough place in one line, it is valid, to put the bracket on the same line as the method call.
Examples
for (int i = 0; i < aNeighbours.length; ++i) { if (p1.x + aNeighbours[i][0] == p2.x) { if (p1.y + aNeighbours[i][1] == p2.y) { return true;
} } }
if (cmd.equals("Größer")) { d.height *= 1.05;
d.width *= 1.05;
} else if (cmd.equals("Kleiner")) { d.height *= 0.95;
d.width *= 0.95;
} else { x = 10;
}
System.out.println(
"Grüße aus Hamburg".regionMatches(
8,
"Greetings from Australia", 8,
2 ) );
Convention 3.7 – Try/catch/finally blocks follow the conventions in this section. Notice the typical indentation of the catch, try and finally block. Include braces even if there is only one statement within a code block.
Example Try {
_traceFile.close();
}
catch (IOException traceFileCloseException) {
System.err.println(“Cannot close trace file “ + _traceFileName);
}
finally {
// clean up any resources that may no longer be needed }
6. Comment Conventions
Comments are a must for maintainability in any language. This section provides the templates for all types of comments in addition to suggested use of comments.
Javadoc makes use of ‘flags’ to generate specific links and markup. These flags include: @author,
@version, @param, @see and @return. Javadoc block comments begin with “/**” on a single line, followed by the comment content, and end with “*/” on a single line. The use of Javadoc flags is not required. If Javadoc flags are used in a package they shall be used consistently. The Javadoc comments in this document suggest how they are to be used, if at all.
A standard file header is needed to identify a file and its history. The information in the file header ties the file and its class to a package, developer, subsystem, project and company.
Example
/***********************************************
<p><b>Kurzbeschreibung:</b>
Die Datei enthält die Klasse Eingabe. Sie dient zum Testen einer streambasierten Eingabe mit Konvertierung durch die Klasse InputStreamReader
<p>
<b>Builded:</b>
javac Eingabe.java mit Java WorkShop 2.0
@author Christoph Riewerts, DaimlerChrysler, M413
@version V1.000 vom 06/09/15
************************************************/
public class Eingabe {
//Hier steht die Klassendefinition }
Javacdoc (javadoc Eingabe.java -author -version) generates the following html-file:
Convention 4.1 – Class, template and interface comment blocks will: State the purpose and describe the advantages and side effects of usage. Describe any assumptions or preconditions to usage, such as hardware restrictions or performance considerations.
Convention 4.2 - Class and Interface comments shall not contain pseudocode or algorithm description, the code itself explains this.
Example /**
* Class: Timer *
* Purpose: To provide a mechanism to initiate processing after * a predetermined amount of time.
*
* Description: The Timer class starts a thread into
* a client method ( timeout() ) after a given time interval.
* The client must explicitly call stopTimeout() upon any errors.
*
* Assumptions: The user of this class has guarded against * thread re-entry problems using synchronise and wait constructs * to protect against data corruption and deadlock.
* */
public class Timer extends Thread {
//Class implementation }
Convention 4.3 - Method comment blocks will contain information which is not obvious from reading the method name and code. If a method is capable of altering the state of anything visible outside the method scope, then that situation must be identified in the method comment block. The following situations require method level comments:
1. Type constraints do not prevent the caller from passing invalid data. (ie. a square root method that takes a real number parameter)
2. Resources are allocated to the caller that must be unallocated by the caller.
java.lang.Object |
+----Eingabe public class Eingabe extends Object
Kurzbeschreibung: Die Datei enthält die Klasse Eingabe. Sie dient zum Testen einer streambasierten Eingabe mit Konvertierung durch die Klasse InputStreamReader
Builded: javac Eingabe.java mit Java WorkShop 2.0 Version:
V1.000 vom 06/09/15 Author:
Christoph Riewerts, DaimlerChrysler, M413 .
.
3. A return value or exception is thrown that indicates a program error. (ie. 0 means no error, -1 means error, 2 means a specific kind of error)
4. A database operation, or network operation is initiated and is not checked.
Convention 4.4 - Method comment blocks shall not contain pseudocode or implementation details, the code itself explains this. For example, stating that a method calculates the area of a circle is acceptable. Describing what mathematical operations are done on the data is redundant information since the code states this. If the method name and code include all the information the caller needs a comment block is not needed.
Example /**
* Inputs:
* productKey: A valid product key.
* dateRange: Contains valid date range for the product.
*
* Output:
* DatabaseCursor: A database cursor for the Product Key.
*
* Preconditions: [exception thrown if violated]
* productKey is valid. [InvalidProductKey]
* The DatabaseInterface has been initailized [unchecked]
*
* Postcondition: A database cursor is open and must be closed
* when not needed anymore.
*
*/
public DatabaseCursor getCursor(int productKey,
ProductDateRange dateRange) {
// Method body }
7. Variable Comments
Convention 5.1 – Member variables should have a ‘//’ comment on the same line as the variable declaration. If the comment is long, it should be placed on the preceding line. ‘//’ comments on the same line as their variables should all line up in the same column.
Example
class myClass {
//The number of myClass instances currently in memory private static int _instances = 0;
public static final int MAX_ROWS = 2000;
public static final int MAX_COLS = 2000;
//The number of clients registered with this instance of myClass;
private int _registered = 0;
private int _rows = 25;
private int _cols = 80;
}
The rows, cols, MAXROWS AND MAX_COLS names are descriptive enough to not need comments.
Convention 6.1 – Inline comments appear above the code that they describe proceeded by one blank line. Inline comments shall not contain blocks of code.
Example
public String getParameter(String theString) {
String myReturnValue = null;
//this implementation is for application clients only.
if (application == FALSE) {
myReturnValue = super.getParameter(theString);
}
//For each possible parameter, explain how to get it...
else if (pram.equals( PARAMETER_TOKEN )) {
myReturnValue = parse.getArgByPos(BASE_POSITION);
}
return myReturnValue;
}
9. Referenced Documents
Coding Standards - DaimlerChrysler; by ADTS, Auburn Hills Java in a Nutshell; by David Flanagan, O’Reilly and Associates