I. Introduction
According to Sun Microsystem’s documentation on code conventions for the Java programming language, code conventions are important to programmers for a number of reasons:
• 80% of the lifetime cost of a piece of software goes to maintenance.
• Hardly any software is maintained for its whole life by the original author.
• Code conventions improve the readability of the software, allowing engineers to
Understand the code more quickly and thoroughly. It is important that we too adhere to the same best practice for the purpose of maintaining clean, easily read and understood, and well documented source codes so that they can easily be understood by our software clients as well as future developers who might need to maintain, enhance, or review these documents.
Any violation to the guide is allowed if and only when it enhances readability and maintainability of the general quality of the code and the generally accepted standards fail to address such.
II. The Java Coding Guidelines
File Names
All java file should start with a capital letter and descriptive but should not exceed 20 characters for the filename.
File suffixes
1. Java source must have a .java extension
2. Java byte code must have a .class extension
3. Properties files must have a .properties extension
File Organization
File size
1. Source file of less than 2000 lines of code is recommended
Source file
2. A Java source file must only contain one public class or one interface.
3. If and only when necessary, private classes may be place below a public class.
5. A Java source file name must be the name of the public class in the file.
Order
1. A Java source file must have the following order:
• File revision history
• Package statement
• Import statements
• Public class and interfaces declaration
• Private class(es) definition(s)
Revision history
The revision history must be in the following format:
/* * Classname * * Copyright notice * * Date Version Author * 2010/1/17 1.0 Florante Navaja * 2010/3/18 1.12 Erwin Llenos * */
Package statement
We will follow the famous java package naming format:
Example: package com.lighthousesoftware.projectname.groupname;
Import statement
We will follow an alphabetical and ascending vertical ordering of import statement format and organize all import according to the package:
Example:
import java.awt.*; import java.beans.*; import java.io.*;
Public class and interface declaration
The following is the order of the class elements:
• Class/interface documentation comment (javadoc)
• Class or interface statement
• Class (static) variables
• Instance variables (members)
• Constructors
• Class (static) methods
• Instance methods
Indentation
Line Length
1. Lines must not be longer than 80 characters
Wrapping Lines
2. Break after a comma
3. Break before an operator
4. Indent 4 spaces from first line within a single statement.
5. Succeeding lines must be aligned with the second line which is
6. spaces indented from the first line.
Comments
Block comments
1. A block comment should be preceded by a blank link to set it apart from the rest of the code.
/* * Block comment here */
Single-line comments
1. Short comments can appear on a single line indented to the level of the code that follows. Total of 80 characters per line includes the single comment if any.
Example:
if(condition) {
System.out.println(“condition set”); /* Print condition set. */
return this.codeID; // Another single line comment
}
Documentation comments
1. Every class, interface, or method must have javadoc style comment for api documentation.
Example:
/** * Class/interface,method description goes here. * * @version 1.82 18 Mar 1999 * @author Firstname Lastname */
Method:
/**
* Return lateral location of the specified position.
* If the position is unset, NaN is returned.
*
* @param x X coordinate of position.
* @param y Y coordinate of position.
* @param zone Zone of position.
* @return Lateral location.
* @throws IllegalArgumentException If zone is <= 0.
*/
public double computeLocation(double x, double y, int zone) throws IllegalArgumentException {
...
}
Declarations
Number per line
1. Only one declaration per line is recommended:
Example:
int level; //indentation level
int size; // size of table
2. Different types must be on different lines:
Example:
int level; Object currentEntry;
Initialization
1. Initialize local variables where they are declared. The only reason not to initialize a variable where it’s declared is if the initial value depends on some computation occurring first.
Placement
2. Variable declarations must be done only at the beginning of blocks.
Example:
void myMethod() {
int int1 = 0; // beginning of method block
if (condition) {
int int2 = 0; // beginning of "if" block
...
}
}
2. Do not hide higher level variable declarations
Example:
int count;
...
myMethod() {
if (condition) {
int count = 0; // AVOID!
...
}
...
}
Class and Interface Declarations
1. No space between a method name and the parenthesis “(“
2. No space between the open parenthesis and the first of the parameter list.
3. Open brace “{“ must appear at the end of the same line as the declaration statement.
4. Closing brace “}” starts a line by itself intended to match it’s corresponding statement, except when it is a null statement the “}” should be after “{“ without space.
5. Every method must be separated by a blank line.
Statements
Simple statements
1. Each line should only contain at most one statement.
Compound statements
1. The enclosed statements should be indented one more level than the compound statement.
2. The opening brace should be at the end of the line that begins the compound statement. The closing brace should be aligned to the beginning of the compound statement unless the body is null where the closing braces should be next to the opening brace “{}”.
3. Braces are used around all statements even on single if-else statements to prevent confusion.
Example:
if (condition) {
return true;
}
Return statements
1. A return statement with a value should not use parenthesis unless they make the return value more obvious in some way.
Example:
return; return myDisk.size(); return (size ? size : defaultSize);
if, if-else statement
1. if- else should have the following form:
if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition2) {
statements;
} else {
default statement;
}
for statements
1. for statements should have the following form:
for (initialization; condition; update) {
statements;
}
while statements
1. A while statement should have the following form:
while (condition) {
statements;
}
do-while statements
1. A do-while statement should have the following form:
do {
statements;
} while (condition);
switch statements
1. A switch statement should have the following form:
switch (condition) {
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
default:
statements;
break;
}
try-catch statements
1. A try-catch statement should have the following format:
try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}
White Spaces
Blank lines
1. One (1) blank line should always be used in the following circumstances:
• Between methods
• Between the local variables in a method and its first statement
• Before a block or single-line comment
• Between logical sections inside a method to improve readability.
2. Two (2) blank lines should always be used in the following circumstances:
• Between sections of a source file
• Between class and interface definitions
Blank spaces
1. Blank spaces should be used in the following circumstances:
• A keyword followed by followed by a parenthesis should be separated by a space.
Example:
while (true) {
….
}
• All binary operators except “.” should be separated from their operands by spaces. Blank spaces should never separate unary operators such as unary minus, increment (“++”), and decrement (“–“) from their operands.
Example:
a += c + d; d++;
• The expressions in a for statement should be separated by blank statements.
Example:
for (expr1; expr2; expr3)
• Casts should be followed by a blank space.
Example:
myMethod((byte) aNum, (Object) x);
• Method parameter list must not have spaces after and before “(“ and “)” respectively. But in between, parameter lists must be separated by a space after comma “,”.
2. A blank space should not be used between a method name and its opening parenthesis. This helps to distinguish keywords from method calls.
Naming Conventions
Packages
1. Package name should be in all lower case and must be in this form:
domain_extension.companydomain.project.module
Classes
1. Class names should be nouns, in mixed case with first letter of each internal word capitalized.
Example:
class Shape; class DiamondShape;
2. Exception classes should be suffixed with Exception.
Example:
class AccessException extends Exception {}
3. Factory classes should be suffixed with Factory.
Example:
Class PointFactory, Class ToyFactory
Interfaces
1. Interface names should be capitalized like class names. Example:
interface Alternator; interface EngineAccelerator;
Methods
1. Method names should be verbs in mixed case with the first letter in lowercase and the first letter of each internal word capitalized. Example:
public void draw(); public double getArea();
2. To shorten method names, omit the type name.
Example:
class Line {
public int getLength() {} // not public int getLineLength() {}
}
…
Line line = new Line();
int length = line.getLength(); // better than line.getLineLength();
3. Rather than the generic get prefix (except when used in a getter/setter), you can use a more descriptive prefix to method names. Example:
shape.computeArea(); //not shape.getArea(); triangle.findNearestNode()// not triangle.getNearestNode();
Variables
1. Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore or dollar sign characters.
2. Parameter variable names should easily refer to its type and intended use.
Example:
public void computeArea(int height, int width) {}
public Staff setNewStaff(Person person, Date hireDate) {}
3. Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary “throwaway” variables like i, x, m in for loops.
Example:
int I; char c; float myWidth;
4. Use is or has prefix when naming boolean variables.
Example:
isSet, isVisible, isFound, hasChildren, hasColor
5. Avoid negated boolean variable names.
Example:
bool isError: // Not isNoError bool isFound; // Not isNotFound
Constants
1. The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores. Example:
static final int MIN_WIDTH = 4;
Abbreviations and acronyms
1. Abbreviations and acronyms should not be uppercase when used as names.
Example:
exportHtmlSource(); //not export HTMLSource() openDvdPlayer(); // not openDVDPlayer()
2. To be more readable, abbreviations in names should generally be avoided.
Example:
computeAverage(); //rather than computeAvg(); catch(Exception exception) // rather than catch(Exception e); catch(IOException ioException) // rather than catch(IOException e);
3. More common abbreviations are better used in its form than the long version.
Example:
renderHtml(); // rather than renderHypertextMarkupLanguage(); callCpu(); // rather than callCentralProcessingUnit();
Terms
Terms in the source code should generally be in the English text since this is a primary and universally understood language.
References
1. Code Conventions for the Java Programming Language
http://java.sun.com/docs/codeconv/
2. Java Programming Style Guidelines
http://geosoft.no/development/javastyle.html
3. The Elements of Java Style
http://www.ambysoft.com/essays/javaCodingStandards.html

