3. Formatting

Oh, the metaphorical blood that has been spilled over code formatting.

The following section describes rules about how your code should be organized visually. It should be noted that the rules listed below are not inarguably the best rules; there are plenty of reasonable alternatives out there. It is important, however, to adhere to the relevant style of the work environment, in this case CS314. For other readers [your TA or instructor], code that follows the style guidelines is easier to understand than code that doesn't. Being able to anticipate conventional formatting of code eliminates time wasted on deciphering the meaning of any unfamiliar structure and formatting.

3.1 Indentation

Each time a curly brace is opened, increase the indent level. When the closing curly brace occurs and ends the code block, the indent should return to the previous indent level. The indent level applies to both code and comments throughout the block defined by the curly braces.

Choose 4 spaces to be your indent level and stay consistent.

Use spaces not tabs.

3.2 Spacing

Java is not a whitespace sensitive language, but maintaining good spacing throughout your program helps your code be more readable for human eyes. Many Java programmers follow the spacing conventions shown below for their programs.

A blank line before every method comment (because every method is commented.)

3.3 One statement per line

Each time you finish a statement with a semicolon, you shall use a new line to begin the next statement.

Note: The exception to this rule is that the for loop header should have its 3 parts all on one line.

3.4 Column limit and line wrapping

No line shall exceed 100 characters in length.

When code that might otherwise legally occupy a single line is divided into multiple lines, this activity is called line-wrapping. Use line-wrapping to break up long lines that would otherwise exceed 100 characters, as described below.

When line-wrapping, each line after the first (each continuation line) should be indented at least one level. Common choices for how much to indent include 2 levels of indentation or lining up elements from the previous line of the long line.

Bad
It’s good that this line is wrapped to maintain the 100 char line limit, but the continued line should be indented at least 1 indentation level and preferably 2.
  public static void method1(String param1, String param2, String param3,
  String param4, String param5) {
    ...
  }
Good
This method header is properly indented and uses 2 levels of indentation for the broken up line.
  public static void method1(String param1, String param2, String param3,
          String param4, String param5) {
    ...
  }
Good
This method header is also properly indented, and lines up elements from the broken up line.
  public static void method1(String param1, String param2, String param3,
                             String param4, String param5) {
    ...
  }

3.5 Exceptions, especially for failure to meet preconditions

Exception code should come at the top of the method. Everything related to checking for and throwing the exception (computing a value to be used in the condition, the if statement itself) counts as exception code. Any code unrelated to the exception conditions / throwing should be placed lower than exception code. This is both an attempt to fail early to avoid unnecessary computation and a readability rule.

If an exception check cannot be checked at the beginning of the method (e.g. requires significant computation / additional statements), check for it when it can be more easily detected as the method continues.

// BAD! This example doesn't check/throw for the exception at the very beginning of the method.
public static int countVowels(String name) {
    int total = 0;
    if (name.length() <= 1) {
        throw new IllegalArgumentException();
    }
    ...
}

Do not attach else statements onto exception checks to connect regular behavior code. Following an exception check, non-exception code should not be placed in an attached else. This is another readability rule (mostly done by convention. Another reason: why indent all of the method's regular behavior code a whole level if the structure is still clear without indenting?) as well as a logic rule. Exception code is fundamentally different than regular method behavior code, and shouldn't be connected to regular behavior with one long if/else structure - doing so almost implies the if/else branches are on the same level of importance or that they are related.

// BAD! This example attaches an 'else' to an exception check. 
// This leads to indenting all the normal behavior code, 
// which makes it a little bit harder to read.
public static int countVowels(String name) {
    if (name.length() <= 1) {
        throw new IllegalArgumentException();
    } else {
        int total = 0;
        ...
    }
}
// GOOD! This one is good! No else attached with regular behavior 
// and the check for exception is at the top of the method.
public static int countVowels(String name) {
    if (name.length() <= 1) {
        throw new IllegalArgumentException();
    }
    int total = 0;
    ...  
}

Note: else ifs that check for more exceptions are fine. Just don't use else to have a branch for the method's normal behavior code. For example the following code structure would be fine.

   if (exceptionCheck) { 
       throw exception1 
   } else if (exceptionCheck2) { 
       throw exception2 
   }
   // non-exception behavior code here

3.6 Curly braces [Preferred, but you can use alternative brace styles]

Again, the metaphorical blood that has been spilled over brace styles is astonishing. The brace rules mentioned below document the style that you will likely see your TAs and lecturers use, but this is optional if you want to use a reasonable (readable) alternative instead. The most important thing is consistency with whatever style you choose.

Example:

public static void method1(int times) {
    for (int i = 0; i < times; i++) {
        if (i % 2 == 0) {
             System.out.print(i);
        } else {
             System.out.print("x");
        }
        System.out.println(" hello");
    }      
}

3.7 Enclose all blocks with curly braces

Although it is not syntactically necessary to enclose single statement blocks controlled by a loop or a conditional, do so in your programming assignments. Omitting these braces can result in maintainability issues if a later editor of your code attempts to add additional lines to the block but fails to add the braces. (Note, some examples and exam questions will omit braces in order to conserve visual space.)

Example:

// #BAD! on assignments
for (int i = 1; i <= MAX; i++) 
    if (i % x == 0) 
        System.out.print(i + " ");
 
// #GOOD!
for (int i = 1; i <= MAX; i++) {
    if (i % x == 0) {
        System.out.print(i + " ");
    }
}
    

 3.8 Remove unnecessary and unneeded code

Consider the program you turn in your final draft. Like the final draft of an English paper or Chemistry lab report, include only what is necessary.

For you solution code especially, remove any and all debugging code, notes to yourself, TODO's, and previous versions of your solution, unused imports, and other comments and / or code that is no longer necessary for your solution.

You can of course save another version of your program with that debugging code and early attempts at solutions, but the code your turn in shall be pristine and without any unnecessary cruft. Take some well-deserved pride in what you have created.