This page includes the Java code style conventions and best practices that you should follow in this course, especially when doing the assignments.

You are required to follow them in your assignments (and encouraged to make it a habit for any Java exercises you write).

However, not all of them will be checked in all assignments. To understand the requirements for each assignment, refer to the table below:

Convention Hello GitHub Assignment 1 Assignment 2
CNAME Class names
MNAME Method names
VNAME Variable names
FORMAT Indentation and brace placement
COMM Code comments
PRIVATE Keep instance field private
PNAME Package names
ORDER Order of elements in a class
USELESS avoid useless code
SCONCAT String concatenation
CLONES Avoid duplicated code
JAVADOC




FORMAT Indentation and brace placement

You should enforce correct format of your Java classes.

For example, it’s hard to find that the code below contains two methods:


public int calculateSum(int[] nums) {
    int sum = 0;
for (int i = 0; i < nums.length; i++) {
  sum = sum + nums[i];}
return sum;
    }

    public int search(int[] nums, int target

{
    for (int i = 0; i < nums.length; i++) {
                     if (target == nums[i]) {
            return i;
        }
        }
return -1;
}


Instead, if we re-write the code like below, it will be clearer:


public int calculateSum(int[] nums) {
    int sum = 0;
    for (int i = 0; i < nums.length; i++) {
        sum = sum + nums[i];
    }
    return sum;
}

public int search(int[] nums, int target) {
    for (int i = 0; i < nums.length; i++) {
        if (target == nums[i]) {
            return i;
        }
    }
    return -1;
}


Automatic formatting

VS Code can help you to correctly format your code:

  • From the Extensions tab, search for “Google Java Format for VS Code” and install it.
  • You can then format the file you have opened:
    • Right click on the file in the editor, and select Format Document, or
    • Use the shortcut:
      • Windows: Shift + Alt + F
      • macOS: F
      • Linux: Ctrl + Shift + I

In the assignment code we provide, we have also added a setting to format the code automatically when you save the file. If you are working on a project where this isn’t already set, all you need to do is add the following to your .vscode/settings.json file:

{
  "editor.formatOnSave": true,
  "[java]": {
    "editor.defaultFormatter": "josevseb.google-java-format-for-vs-code"
  }
}

If the .vscode/settings.json file doesn’t already exist, you can create it and then add the above code to it.


Indenting with spaces instead of tabs

To configure VS Code to use spaces instead of tabs, you can add the following to your .vscode/settings.json file:

{
  "editor.insertSpaces": true,
  "editor.detectIndentation": false,
  "editor.tabSize": 2
}


Note, if you already have other settings in your .vscode/settings.json file, you can just add these three lineswithin the existing {}. Do not add a second sect of {}. For example, your complete .vscode/settings.json file might look like this:

{
  "editor.formatOnSave": true,
  "[java]": {
    "editor.defaultFormatter": "josevseb.google-java-format-for-vs-code",
  },
  "editor.insertSpaces": true,
  "editor.detectIndentation": false,
  "editor.tabSize": 2
}


Saving the settings as default for other projects

You can also change these settings via the VS Code settings. To do this, open the settings (by clicking the gear icon in the bottom left).

First, search for tabSize. Make sure you have these settings, remembering to do this for both the User and Workspace tabs:

Edit


Next, search for insertSpaces. Make sure you have these settings, remembering to do this for both the User and Workspace tabs:

Edit


You can also confirm it’s correct by quickly looking at the bottom right of the VS Code window. It should say Spaces: 2:

Edit




CNAME Class names

Class names should be written in UpperCamelCase (the first letter of each internal word capitalised)

See here the instructions for Camel Case: https://google.github.io/styleguide/javaguide.html#s5.3-camel-case Note that, as the instructions explains, you need to lowercase everything (including acronyms) (e.g., JavaFX -> JavaFx).

Class names should be nouns or noun phrases. For example, Car or ArrayList. It is OK if a class name starts with an adjective but the class name must contain a noun. For example, LinkedList is a valid class name as Linked is an adjective and List is a noun.

A JUnit test class has a name that ends with Test. If it covers a single class, its name is the name of that class plus Test, for example CarTest.




MNAME Method names

Method names should be written in lowerCamelCase (the first letter lowercase, with the first letter of each internal word capitalised).

See here the instructions for Camel Case: https://google.github.io/styleguide/javaguide.html#s5.3-camel-case Note that, as the instructions explains, you need to lowercase everything (including acronyms).

For example you should use decideAction but NOT decide_action or decideaction.

Method names should start with a verb.




VNAME Variable names

Variable names (this includes field and parameter variables) are written in lowerCamelCase (the first letter lowercase, with the first letter of each internal word capitalised)

See here the instructions for Camel Case: https://google.github.io/styleguide/javaguide.html#s5.3-camel-case Note that, as the instructions explains, you need to lowercase everything (including acronyms).

For example, we should use initialAmount but NOT initial_amount or initialamount.

Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed. Variable names should be short yet meaningful.

One-character variable names should be avoided except for temporary “throwaway” variables (e.g., iterator i of a for loop).

Names representing final and static variables must be all uppercase using underscore to separate words (e.g., MAX_ITERATIONS, COLOR_RED)

Plural form should be used on names representing a collection of objects. For example, List<Car> cars and int[] values.




COMM Code comments

In Java you can write comments with // or multiple lines comments with /* ... */

Comments in the code should 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. Do not comment every single line of code, only where necessary.

For example, you should NOT write comments like this:


// set isOpen to false
isOpen = false;


Regarding code frequency, we are checking for the following:

  • You should comment at least 5% of lines of code in a method, and
  • You should comment at most 60% of lines of code in a method.

Note that this will be checked only for methods with 6 or more lines of code (excluding blank lines or lines containing only braces).




PRIVATE Keep instance field private

When you declare instance fields, always make them private and use getter/setter to access them. This protects data from unwanted access and a level of data hiding. Alternatively, you can make them protected if they should be accessed by the subclasses.


public class Point {

	public double x;
	public double y;

	public Point(double x, double y) {
		this.x = x;
		this.y = y;
	}

}


Instead, you should do like this:


public class Point {

	private double x;
	private double y;

	public Point(double x, double y) {
		this.x = x;
		this.y = y;
	}

	public void setX(double x) {
		this.x = x;
	}

	public void setY(double y) {
		this.y = y;
	}

	public double getX() {
		return x;
	}

	public double getY() {
		return y;
	}

}


Note that getter and setter methods can be generated automatically by VS Code. You just need to right-click inside a Java class, and choose Source actions…Generate getters and setters.




PNAME Package Name

In a project, put related Java class into the same package (packages are acting like folders).

To avoid conflict with class or interface names, package names should contain lowercase letter only, for example, use mypackage but NOT myPackage.

Package names must follow the directory structure. For example, the Java class A.java located in src/main/java/nz/ac/auckland/se281/A.java must have as package declaration pacakge nz.ac.auckland.se281;.




ORDER Order of elements in a class

When creating a class, use the following order for the elements

  1. package
  2. imports
  3. class declaration
  4. inner classes
  5. static fields
  6. static methods
  7. instance fields
  8. constructors
  9. instance methods

For example, you should never write a class like the code below. It is difficult even to find out how many fields are in the class:


import java.util.ArrayList;
import java.util.List;

public class Book {

	public void applyDiscount(double discount) {
		this.discount = discount;
	}

	private String name;
	private double price;
	public Book(String name, double price) {
		this.name = name;
		this.price = price;
		Book.allBooks.add(this);
	}

	private double discount = 1;
	public double getPrice() {
		return this.price * this.discount;
	}

	static List<Book> allBooks = new ArrayList<>();
}


Instead, it is clearer if to write the code like this:


import java.util.ArrayList;
import java.util.List;

public class Book {

	static List<Book> allBooks = new ArrayList<>();

	private String name;
	private double price;
	private double discount = 1;

	public Book(String name, double price) {
		this.name = name;
		this.price = price;
		Book.allBooks.add(this);
	}

	public void applyDiscount(double discount) {
		this.discount = discount;
	}

	public double getPrice() {
		return this.price * this.discount;
	}
}




JavaDoc

JavaDoc is commonly used for commenting classes, methods, and fields. The key advantage of the JavaDoc is that it can be used to automatically generate standard documentation in HTML format (we will not do it in this course).

Here are the Oracle official guide on how to write JavaDoc: https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html

For methods, the JavaDoc should explain the usage and behaviour of a method, also it should explain the meaning of the parameter list (with @param tags), the return value (with @return tags), and any throw exceptions (with @throws tags).

For classes, the JavaDoc should explain the purpose of the class.

After you wrote a method declaration, VS Code can automatically generate a JavaDoc template for you (type /** and press enter).

For example, this is the JavaDoc of the method add of the JDK class ArrayList

/**
* Inserts the specified element at the specified position in this
* list. Shifts the element currently at that position (if any) and
* any subsequent elements to the right (adds one to their indices).
*
* @param index index at which the specified element is to be inserted
* @param element element to be inserted
* @throws IndexOutOfBoundsException {@inheritDoc}
*/
public void add(int index, E element) {
....

You should fill the template with one or more sentences describing the behaviour of the method. After that, you should leave one empty line and you should add a short description for each method parameter, return value, and throw (checked) exception.

For example, consider the following method:

public int addNumbers(int n1, int n2) {
	return n1 + n2;
}

In VS Code if you type /** on top of the method and press Enter

public int addNumbers(int n1, int n2) {
	return n1 + n2;
}

press Enter

/**
public int addNumbers(int n1, int n2) {
	return n1 + n2;
}

VS Code will generate the JavaDoc template:

/**
*
* @param n1
* @param n2
* @return
*/
public int addNumbers(int n1, int n2) {
	return n1 + n2;
}

Then you can fill the template:

/**
* adds two integer numbers and return the sum of these two numbers

* @param n1 first number
* @param n2 second number
* @return the sum of n1 and n2
*/
public int addNumbers(int n1, int n2) {
	return n1 + n2;
}




USELESS avoid useless code

Your program should be free of code that does not play any role in the program. One example of this is code that is commented out, as it is not be used anymore:


public int calculateSum(int[] nums) {
    int sum = 0;
    for (int i = 0; i < nums.length; i++) {
        // System.out.println(nums[i]);
        sum = sum + nums[i];
    }
    return sum;
}


Another example of pointless code is unused variables or imports:


import java.util.Random;  // unused import

public class Calculator {

    public int calculateSum(int[] nums) {
        int sum = 0;
        for (int i = 0; i < nums.length; i++) {
            int currNum = nums[i];  // unused variable
            sum = sum + nums[i];
        }
        return sum;
    }

}




SCONCAT String concatenation

Frequent string concatenation decreases the performance significantly, that is, you should not do string concatenation in a loop like the code below:


String nums = "";

for (int i = 0; i < 10; i++) {
    nums = nums + i;
}


Rather than doing string concatenation again and again, using a StringBuilder improves performance a lot:


StringBuilder sb = new StringBuilder();
for (int i = 0; i < 10; i++) {
    sb.append(i);
}
String nums = sb.toString();




CLONES Avoid duplicated code

If you find yourself copy-and-pasting your code in different parts of your Java class, consider creating a private (protected if you want to write unit tests for it) method to avoid duplicated code and promote code reuse. This improves maintainability because when code is copied, bugs need to be fixed at multiple places, which is inefficient and error-prone.




More on Java conventions

You can find some more Java conventions when writing code here:

https://google.github.io/styleguide/javaguide.html