We Can Code IT Java Style Guide

Purpose

The Java language gives you the ability to write code however you would like. While this might sound like a great thing, you might want to consider the consequences of writing code however you want. The phrase "With great power comes great responsibility." comes to mind when writing code without a style guide. There is nothing stopping you from writing your source code in a fashion that is confusing to others, including your future self. There is also nothing stopping you from writing code that is easy to understand. Many employers, organizations, and projects use style guides that help keep code easier to understand. These style guides work by laying out some house rules for developers working on their code base to follow.


The Guide

Note: We have borrowed some points and examples from the Java Ranch's style guide, but our guide has subtle differences. You can find a link to their guide in the reference section below.

Formatting

Indentation

  • Spaces, not tabs. All IDEs and text editors read spaces the same way, some interpret tabs differently.

  • Indents are 4 spaces.

  • Closing braces are always on new lines and indentation line up with their construct.

    public void foo() {
        while (bar > 0) {
            System.out.println();
            bar--;
        }
    
        if (oatmeal == tasty) {
            System.out.println("Oatmeal is good and good for you");
        } else if (oatmeal == yak) {
            System.out.println("Oatmeal tastes like sawdust");
        } else {
            System.out.println("tell me pleeze what iz dis 'oatmeal'");
        }
    }
  • All if, while and for statements must use braces even if they control just one statement.

    if (superHero == theTick) System.out.println("Spoon!");  // NO!
    
    if (superHero == theTick)
        System.out.println("Spoon!");  // NO!
    
    if (superHero == theTick) {
        System.out.println("Spoon!");
    }  // YES!                      

    Spacing

  • All method names should be immediately followed by a left parenthesis.

    foo (i, j); // NO!
    foo(i, j);  // YES!
  • All array dereferences should be immediately followed by a left square bracket.

    args [0];  // NO!
    args[0];   // YES!
  • Binary operators should have a space on either side.

    a=b+c;          // NO!
    a = b+c;        // NO!
    a=b + c;        // NO!
    a = b + c;      // YES!
    
    z = 2*x + 3*y;         // NO!
    z = 2 * x + 3 * y;     // YES!
    z = (2 * x) + (3 * y); // YES!
  • Unary operators should be immediately preceded or followed by their operand.

    count ++; // NO!
    count++;  // YES!
    
    i --;     // NO!
    i--;      // YES!      
  • Commas and semicolons are always followed by whitespace.

     for (int i = 0;i < 10;i++)   // NO!
     for (int i = 0; i < 10; i++) // YES!
    
     getPancakes(syrupQuantity,butterQuantity);  // NO!
     getPancakes(syrupQuantity, butterQuantity); // YES!
  • All casts should be written with no spaces.

    (MyClass) v.get(3);  // NO!
    ( MyClass )v.get(3); // NO!
    (MyClass)v.get(3);   // YES!
  • The keywords if, while, for, switch, and catch must be followed by a space.

     if(hungry)  // NO!
     if (hungry) // YES!
    
     while(pancakes < 7)  // NO!
     while (pancakes < 7) // YES!
    
     for(int i = 0; i < 10; i++)  // NO!
     for (int i = 0; i < 10; i++) // YES!
     
     catch(TooManyPancakesException e)  // NO!
     catch (TooManyPancakesException e) // YES!

    Blank Lines

Limit your empty lines to a single empty line when you want to separate sections of code.

Class Member Ordering

class Order {
    // fields (attributes)

    // constructors

    // methods
}

Maximum Line Length

Avoid making lines longer than 120 characters. Long lines are frustrating to deal with. If you have nested indentations that push your code to the right of your editor, consider extracting methods to simplify your code.

Parentheses

Use them! They help specify order of precedence and simplify expressions.

Identifiers

All identifiers use letters ('A' through 'Z' and 'a' through 'z') and numbers ('0' through '9') only. No underscores, dollar signs or non-ascii characters.

Classes and Interfaces

All class and interface identifiers will use upper camel case (a.k.a. Pascal case). The first letter of each word in the name will be uppercase, including the first letter of the name. All other letters will be in lowercase, except in the case of an acronym, which will be all upper case.

Customer
SalesOrder
TargetURL
URLTarget

Packages

Package names will use lower case characters only. Try to keep the length under eight (8) characters. Multi-word package names should be avoided. Exceptions to length can be made for base package names.

common
core
lang

Enum Instances and Constants Identifiers for enum instances and values that are declared final and static and are intended to be a constant value throughout the application will use upper case characters only and have words separated by underscores.

public enum CarColors {
    FIRE_ENGINE_RED, BURGUNDY, SKY_BLUE, JET_BLACK
}

public static final String DEFAULT_NAME = "Mel";

All Other Identifiers

All other identifiers, including (but not limited to) fields, local variables, methods and parameters, will use the following naming convention known as lower camel case, or just camel case. The first letter of each word in the name will be uppercase, except for the first letter of the name. All other letters will be in lowercase, except in the case of an embedded acronym, which will be all uppercase. Leading acronyms are all lower case.

customer
salesOrder
addToTotal()
targetURL
urlTarget

Hungarian Notation and Scope Identification Hungarian notation and scope identification are not allowed.

public class Person {
    private String sFirstName; // NO! (Hungarian notation: s for String)
    private String firstName;  // YES!

    private String mLastName;  // NO! (Scope identification: m for member variable)
    private String _lastName;  // NO! (Scope identification: _ for member variable)
    private String lastName;   // YES!

    // ...
}

Test Code Test code is permitted to use underscores in identifiers for methods and fields. Code for testing other code often needs to be able to refer to existing identifiers, but also be able to append other qualifiers to the name. This is easier to read if an additional delimiter is allowed.

Example:

Code to test a method double eatSomePie(double amount) may use variables such as:

eatSomePie_count
eatSomePie_amount
eatSomePie_return
eatSomePie_exception

Coding

Constructs to Avoid

  • Never use do..while. -- Do not use do..while loops. When encountering a loop, the first thing the programmer wants to know is what terminates the loop. If you have that logic at the bottom, it is harder to read. So rather than:

    boolean done = false;
    do {
        ...
    } while (!done)

    use:

    boolean done = false;
    while (!done) {
       ...
    }
  • Never use return in the middle of a method. Return is to be used at the end of a method only.

  • Never use continue. Using continue makes it difficult to later break the construct into smaller constructs or methods. It also forces the developer to consider more than one end point for a construct.

  • Never use break other than in a switch statement. Break is used only for switch statement control.

Do Not Compound Increment or Decrement Operators

Use a separate line for an increment or decrement.

    foo(x++); // NO!

    foo(x);   // YES!
    x++;


    y += 100 * x++;  // NO!

    y += 100 * x;    // YES!
    x++;  
Note: i++ and ++i are equally fast, and i++ seems more consistent with the rest of the language. Since the above prevents any use of a case where ++i could make a difference, never use pre- increment/decrement.

Initialization

Declare variables as close as possible to where they are used.

    int totalWide;
    int firstWide = 20;
    int secondWide = 12;
    firstWide = doFoo(firstWide, secondWide);
    doBar(firstWide, secondWide);
    totalWide = firstWide + secondWide;         //  wrong!

    int firstWide = 20;
    int secondWide = 12;
    firstWide = doFoo(firstWide, secondWide);
    doBar(firstWide, secondWide);
    int totalWide = firstWide + secondWide;     //  right!

    int secondWide = 12;
    int firstWide = doFoo(20, secondWide);
    doBar(firstWide, secondWide);
    int totalWide = firstWide + secondWide;     //  even better!

Access

All fields must be private, except for some constants.

Self-Documenting Code

"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler, Refactoring: Improving the Design of Existing Code

Strive to make your code read like well written prose. Rather than using comments to describe what your code does, use identifiers that convey the purpose of the methods and variables you write. In the future if the code changes, you don't have to update your comments.

Instead of:

    if ( (hero == theTick) && ( (sidekick == arthur) || (sidekick == speak) ) )

Use:

    boolean isTickSidekick = ( (sidekick == arthur) || (sidekick == speak) );
    if ( (hero == theTick) && isTickSidekick )

Or:

Instead of:

    public static void happyBirthday(int age) {
        // If you're in the US, some birthdays are special:
        // 16 (sweet sixteen)
        // 21 (age of majority)
        // 25, 50, 75 (quarter centuries)
        // 30, 40, 50, ... etc (decades)
        if ((age == 16) || (age == 21) || ((age > 21) && (((age % 10) == 0) || ((age % 25) == 0)))) {
            System.out.println("Super special party, this year!");
        } else {
            System.out.println("One year older. Again.");
        }
    }

Use:

    public static void happyBirthday(int age) {
        boolean sweetSixteen = (age == 16);
        boolean majority = (age == 21);
        boolean adult = (age > 21);
        boolean decade = (age % 10) == 0;
        boolean quarter = (age % 25) == 0;

        if (sweetSixteen || majority || (adult && (decade || quarter))) {
            System.out.println("Super special party, this year!");
        } else {
            System.out.println("One year older. Again.");
        }
    }

References

  • Java Ranch Style Guide -- Our style guide is heavily influenced by theirs.
  • Oracle's Java Style Guide Oracle's original Java style guide for Java.
  • Google's Java Style Guide -- Google's coding standards for source code in the Java™ Programming Language.
  • AOSP Java Style Guide -- Strict rules for contributing Java code to the Android Open Source Project (AOSP). (Note: this style guide has some C/C++ opinions bleeding in from the fact that it is for Android, but it's a good example of a different style guides.)

Closing

While use of a style guide will not guarantee clean code, it helps us avoid many common pitfalls that plague hard to read code. Following a style guide is a good first step towards clean coding and a professional obligation for developers working in collaborative environs.