Index

Formatting Code

Index


Overview


Formatting code is hugely important. It allows you to read your code easily. It allows others to read your code most easily.

Example #1 -- Method Formatting


Method Code Before Formatting


public void showEvenNumberCount()
{
int count;

count = 0;
for (int i=1; i<=10; i++)
{
if (i %2 == 0)
{
	count++;
}

}
System.out.println("even number count from 1 to 10 is: " + count);

}


Method Code After Formatting


	public void showEvenNumberCount() {
		int count;

		count = 0;
		for (int i = 1; i <= 10; i++) {
			if (i % 2 == 0) {
				count++;
			}
		}
		System.out.println("even number count from 1 to 10 is: " + count);
	}


Example #2 -- A Formatted Class


public class Foo {
	
	/* -------------------------------------
	Instance methods */

	public void showEvenNumberCount() {
		int count;

		count = 0;
		for (int i = 1; i <= 10; i++) {
			if (isEven()) {
				count++;
			}
		}
		System.out.println("even number count from 1 to 10 is: " + count);
	}
	
	public boolean isEven(int n) {
		return n % 2 == 0;
	}
	
	/* -------------------------------------
	main */

	public static void main(String[] args) {
		Foo foo;
	
		foo = new Foo();
		foo.showEvenNumberCount();
	}

}



Example #3 -- Advanced Formatting (Optional Block Brackets)


When a conditional statement has only one block statement it may optionally be streamlined by removing the block symbols (this is not required, but is optional per your preference). Advantage is does simplify things further.

Note that the if block in our previous example only has one statement
count++
. Thus, we optionally may remove the {} block brackets. Similarly, the for loop also has only one statement (the if statement). So again we may optionally may remove it's {} block brackets. This is optional and per your preference.

	public void showEvenNumberCount() {
		int count;

		count = 0;
		for (int i = 1; i <= 10; i++)
			if (isEven())
				count++;
		System.out.println("even number count from 1 to 10 is: " + count);
	}