Java Code Conventions (Style guide)


TABLE OF CONTENTS
These style rules should be followed when writing assignements.

What is a "Style guide"?

A style guide is a set of mandatory (obligatoriska!) requirements for layout and formatting. Uniform style makes it easier for your instructor and your grader to grasp the essence of your programs quickly. It is also easier for you to read code from your instructor and classmates. You will really appreciate that if you do a team project.

Why have code conventions

Code conventions are important to programmers for a number of reasons: Therfore it is important that all involved in a course or members of a development team use the same set of rules of syntactic layout. Otherwise, anyone that has to read the source-code of different authors constantly have to get used to new layouts instead of spending that energy on more important issues, such as understanding the underlaying algorithm. Some layouts are more readable since most skilled programmers find them to reveal more of the structure of the underlaying algorithm. A common misunderstanding is that all source-code that provide the same functionality is just as good; it is equally important that the source-code is as readable as possible if there is not a really good reason for obfuscation (and more efficient code is not such a reason if there is not an established efficiency problem).

It is important to have a reasonable indentation style and to use it consistently in your assignments!
For the conventions to work, every person writing software must conform to the code conventions. Everyone.

If you already have programming experience, in Java or another language, you may be initially uncomfortable at giving up some fond habits. However, it is a sign of professionalism to set aside personal preferences in minor matters and to compromise for the benefit of your group.

Acknowledgments

This document reflects the Java language coding standards presented in the Java Language Specification, from Sun Microsystems, Inc. It has been altered to conform with pt coding conventions (mostly by skipping parts of the original dokument).

Adapted with permission from JAVA CODE CONVENTIONS. Copyright 1995-1999 Sun Microsysytems, Inc. All rights reserved. The Java Code Conventions Web site is at: http://java.sun.com/docs/codeconv/



TABLE OF CONTENTS

Indentation

General

Four (4) spaces should be used as the unit of indentation.

If I try to formulate a simple "rule" for how to indent it would be (perhaps I have forgotten some more special cases)
A '{' always cause a new line and indentation on the next line e.g.

if (...) {
    xxxxxxx
A '}' always cause a new line, reindentation and usually one more new line e.g.
if (...) {
    xxxxx
}   
nnnnnn
Some exceptions exist, for example before else if
if (...) {
    xxxxx
} else if (...) {
    xxxxx
}

Avoid lines longer than 80-100 characters, since they're not handled well by many terminals and tools and long lines are hard to read.

The first style below is usually better because it saves space. If you desperately want more space use the second style. (The only difference is the placement of the starting block parenthesis({). Sun recomends the first alternative.

class Syntax {
    public static void main( String args[] ) {
        int aVariable = 5;                           // usually declare all variables at top
        if ( aVariable < 6 ) {                       // always use a block ({})
            System.out.println( "True" ) ;
        } else {
            System.out.println( "False" ) ;
        }
    }
}
// ************* second, not so god, style
class Syntax 
{
    public static void main( String args[] ) 
    {
        int aVariable = 5;
        if ( aVariable < 6 ) 
        { 
            System.out.println( "True" ) ;
        } else
        {
            System.out.println( "False" ) ;
        }
    }
}

Always use blockstatements!

if (door.isOpen()) {
    if (resident.isVisible()) {
        resident.greet("Hello!");
    }
} else {
    door.bell.ring();
}	

This is one reason for blockstatements: As in C and C++, the if statement of the Java programming language suffers from the so-called "dangling else problem," illustrated by this misleadingly formatted example:

The problem is that both the outer if statement and the inner if statement might conceivably own the else clause. In this example, one might surmise that the programmer intended the else clause to belong to the outer if statement. The Java programming language, like C and C++ and many programming languages before them, arbitrarily decree that an else clause belongs to the innermost if to which it might possibly belong.

Another reason is that a very common bug is to add another statement witout adding a block (if there are no block to start with).

Wrapping Lines

When an expression will not fit on a single line, break it according to these general principles:

Examples:

Here are some examples of breaking method calls:

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 

Following are two examples of indenting method declarations. The first is the conventional case. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.

//CONVENTIONAL INDENTATION
someMethod(int anArg, Object anotherArg, String yetAnotherArg,
           Object andStillAnother) {
    ...
}

//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
private static synchronized horkingLongMethodName(int anArg,
        Object anotherArg, String yetAnotherArg,
        Object andStillAnother) {
    ...
}
Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:

//DON'T USE THIS INDENTATION
if ((condition1 && condition2)
    || (condition3 && condition4)
    ||!(condition5 && condition6)) { //BAD WRAPS
    doSomethingAboutIt();            //MAKE THIS LINE EASY TO MISS
} 

//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
        || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
} 

//OR USE THIS
if ((condition1 && condition2) || (condition3 && condition4)
        ||!(condition5 && condition6)) {
    doSomethingAboutIt();
} 

TABLE OF CONTENTS

Indentation rules for the usual statements

Simple Statements

Each line should contain at most one statement. Example:

argv++;       // Correct
argc--;       // Correct  
argv++; argc--;       // AVOID!

Compound Statements

Compound statements are statements that contain lists of statements enclosed in braces "{ statements }". See the following sections for examples.


TABLE OF CONTENTS

Selection

if (boolean expression) {
    statements
}
Conditional (Use block statements even if there are only one statement)
if (boolean expression1) {
    statements
} else if (boolean expression2) {
    statements
} else {
    statements
}
Conditional with else
switch (integer expression) {
     case value :
        statements
        break; // exit the switch
     case value1 :
        /* falls through */
     case value2 :
        statements
        break; // exit the switch     ...
    default :
        statement
        break; // exit the switch
}
switch
(integer expression has to be of type int or char)
Each case selects one possible value.
 
This one selects two.
 
 
Don't forget "break"

Every time a case falls through (ie. doesn't include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the /* falls through */ comment.

Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.

Example: if statement and it's indentation (always use a block ”{ }”):

Specifically observe that one normally never writes The correct way of writing this is And you never compare a boolean expression to a boolean litteral as in (if (a==true) ...).
TABLE OF CONTENTS

Loops

for (initializer; bool-expr; change) {
    statements
}
for loop
Used when we know the number of turns.
All of initializer, test and change are optional
initializer and change may be several comma separated statements.
initializer is executed once, the body is executed as long as boolean expression is true and change is executed after each iteration of the loop.
while (boolean expression) {
    statements
}
while loop, executes 0 or more times
do {
    statements
} while (boolean expression);
do loop, executes 1 or more times

Example, loop statemenst and their indentation (always use a block ”{ }”):

Simple rules: The for-statement should be used to model the concept of "doing something for every member of set of fixed size" and nothing else. Most of the time the set is a range of integers and we would like to do something with every number in the range (either in order or in reversed order). In any other case when you need a loop, use the while or do -statement. A few reasons for this are Sometimes one would like to step more than one element in the range, to model the concept of doing something with every other, every third, etc., number in a range. However, it is not suitable to use a for-statement to do something with every floating-point number in [0.0, 0.1, 0.2, .., 1.0] in the following way.

This is because a floating-point number is just an approximation of a real number, and almost every time you make a floating-point arithmetic operation you loose a little more precision. In the example above we keep on making floating-point additions to d and for every operation d becomes more imprecise. However, integer operations in programming languages, if within the bounds of the used integer type, are always exact. Hence, if we rewrite the code above as follows even the last d that we do something with is only subject to one floating-point operation, instead of nine.

There are similar ways to construct most useful series of floating-point numbers.


TABLE OF CONTENTS

try-catch Statements

A try-catch statement should have the following format:

try {
    statements;
} catch (ExceptionClass e) {
    statements;
}

A try-catch statement may also be followed by finally, which executes regardless of whether or not the try block has completed successfully.

try {
    statements;
} catch (ExceptionClass e) {
    statements;
} finally {
    statements;
}

TABLE OF CONTENTS

Expressions

The first expression, with no spaces, is not very readable. Use the last or possibly second alternative. Se also "White Space".
if(a==B&&c==d||m==4) ...

if(a==B && c==d || m==4) ...
if(a == B && c == d || m == 4) ...
Always use spaces in assignements.
moms = 25.0;

TABLE OF CONTENTS

Identifiers

Start the names of classes with uppercase letters and start the names of variables, objects and methods with lowercase letters.
Only uppercase and lowercase ASCII Latin letters A-Ö, and a-ö, the ASCII underscore (_) or digits 0-9 are allowed in identifiers. (You should probably avoid åÅäÄöÖ.)

Variables should be named according to the following rules.

IdentifierTo be written as
Class names ClassNames
Variable and method namesvariableAndMethodNames
Object namesobjectNames
Names of constants NAMES_OF_CONSTANTS


TABLE OF CONTENTS

Constants

Do not use magic numbers! A magic number is a numeric constant embedded in code, without a constant definition. Any number except -1, 0, 1, and 2 is considered magic:
if (p.getX() < 300) // Don't
Use final variables instead:
	
final double WINDOW_WIDTH = 300;
. . .
if (p.getX() < WINDOW_WIDTH) // OK

TABLE OF CONTENTS

Declarations

One Per Line

One declaration per line is recommended since it encourages commenting. In other words,
    int level; // indentation level
    int size;  // size of table

is preferred over

    int level, size;

Do not put different types on the same line. Example:

    int foo,  fooarray[]; //WRONG!

Note: The examples above use one space between the type and the identifier. Another acceptable alternative is to use tabs, e.g.:

int      level;         // indentation level
int      size;          // size of table
Object   currentEntry;  // currently selected table entry

Initialization

Try to initialize local variables where they're 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

Put declarations only at the beginning of blocks. (A block is any code surrounded by curly braces "{" and "}".) Don't wait to declare variables until their first use; it can confuse the unwary programmer and hamper code portability within the scope.

void myMethod() {
    int int1 = 0;         // beginning of method block

    if (condition) {
        int int2 = 0;     // beginning of "if" block
        ...
    }
}

The one exception to the rule is indexes of for loops, which in Java can be declared in the for statement:

for (int i = 0; i < maxLoops; i++) { ... }

Avoid local declarations that hide declarations at higher levels. For example, do not declare the same variable name in an inner block:

int count;
...
myMethod() {
    if (condition) {
        int count = 0;     // AVOID!
        ...
    }
    ...
}

Class and Interface Declarations

When coding Java classes and interfaces, the following formatting rules should be followed:

class Sample extends Object {
    int ivar1;
    int ivar2;

    Sample(int i, int j) {
        ivar1 = i;
        ivar2 = j;
    }

    int emptyMethod() {}

    ...
}

TABLE OF CONTENTS

Comments

Java programs can have two kinds of comments: implementation comments and documentation comments. Implementation comments are delimited by /*...*/, and //. Documentation comments (known as "doc comments") are Java-only, and are delimited by /**...*/. Doc comments can be extracted to HTML files using the javadoc tool.

Implementation comments are meant for commenting out code or for comments about the particular implementation. Doc comments are meant to describe the specification of the code, from an implementation-free perspective. to be read by developers who might not necessarily have the source code at hand.

Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. Comments should contain only information that is relevant to reading and understanding the program. For example, information about how the corresponding package is built or in what directory it resides should not be included as a comment.

Discussion of nontrivial or nonobvious design decisions is appropriate, but avoid duplicating information that is present in (and clear from) the code. It is too easy for redundant comments to get out of date. In general, avoid any comments that are likely to get out of date as the code evolves.

Note:The frequency of comments sometimes reflects poor quality of code. When you feel compelled to add a comment, consider rewriting the code to make it clearer.


TABLE OF CONTENTS

White space

Blank Spaces

Blank spaces should be used in the following circumstances:
    a += c + d;
    a = (a + b) / (c * d);
    
    while (d++ = s++) {
        n++;
    }
    printSize("size is " + foo + "\n");

    for (expr1; expr2; expr3)

    myMethod((byte) aNum, (int) x);
    myMethod((int) (cp + 5), ((int) (i + 3)) + 1);

Blank Lines

Blank lines improve readability by setting off sections of code that are logically related.

One blank line should always be used in the following circumstances:

Two blank lines should always be used in the following circumstances:


TABLE OF CONTENTS

Methods


TABLE OF CONTENTS

Programs

Always put main method last in the class.
TABLE OF CONTENTS

Table Of Content: JavaTM Code Conventions (Style guide)

What Is a "style guide"?
Why Have Code Conventions Acknowledgments
Indentation
General
Always use blockstatements!
Wrapping Lines
Indentation rules for the usual statements
Simple Statements
Compound Statements
Selection
Loops
try-catch Statements
Expessions
Identifiers
Constants
Declarations
One Per Line
Initialization
Placement
Class and Interface Declarations
Comments
White space
Blank Spaces
Blank Lines
Methods
Programs

TABLE OF CONTENTS

This document was last changed by Erland Holmström, mail: erland please add @chalmers.se