Code Style Guidelines

Having a good coding style makes your code readable and easier to understand for everyone reading it. The idea is to treat it as if another programmer will continue to maintain the code after you. Follow each of these basic style guidelines which you will be graded on:

  1. File header: At the top of your file, include a 2-4 sentence summary about the file. Include your cs11wxxx account and PID as well as references to sources used.
  2. Class Header: Describe in 1-2 sentences the purpose and capabilities of your Class. Talk about important instance variables if there are any.
  3. Method Header: Describe method functionality briefly and mention special cases if there are some. Include arguments and return value descriptions.
  4. Use proper indenting: Indent each block of code consistently (e.g., method body, loop body). Line up the lines in the block so that they are all indented to the same degree.
    1. See examples of this in the book and in the code samples below.
  5. Use descriptive variable names: The names of your variables should describe the data they hold. Almost always, your variable names should be words (or abbreviations), not single letters. An exception to this rule is loop control variables that designate an index in an array. i, j, and k are accepted names for these. It is preferable to have clear, longer, reasonable variable names in your code overall (example: letter1 and letter2 vs lowerCaseLetter and upperCaseLetter).
  6. Avoid using magic numbers: Magic numbers are direct usages of numerical or text values throughout the code that should be refactored for readability and easier code maintenance. These values should be stored in a variable (usually named with caps and underscores). These variables names should also be descriptive and placed in the beginning of the class/method grouped together.
    1. See examples of this in the book and in the code samples below.
  7. Write short methods: Break your methods up into sub-methods if they are getting too complicated or long. If you find yourself having to repeat typing similar code (can be copy-pasted), then modularize the code by making a new helper method.
  8. Write short lines: Each line of code should be no longer than 80 characters, so it can fit in a reasonable size window. Your vim setup should highlight lines that are longer than 80 characters. You may find that you need to wrap your lines of code to preserve the character limit (examples below). You can do so by following these general principles:
    1. Break after a comma (example 1, 3 and 4)
    2. Break before an operator (example 2 and 5)
    3. Align the new line with the beginning of the expression at the same level of the previous line (example 4 and 5)
    4. If the above rules lead to confusing code or to code that's squished up against the right margin, indent 8 spaces instead. (all examples)
  9. Write appropriate inline comments: Each piece of logic should be documented if it is not self-explanatory. You do not need to comment intensively, but do make sure that you comment in places where people may feel confused about. (eg. code for creating an arraylist is self-explanatory enough at most times, therefore you do not always need to write inline comments for that. A nested for loop may be confusing, so you may want to write some comments for that.)

Example Method Code Style

 /** Return the score of the letter in scrabble.
   * @param letter The letter in question
   * @return The scrabble value of the letter
   * */
 private int letterScore( char letter )
 {
   char lowerCaseLetter = Character.toLowerCase( letter );
   switch (lowerCaseLetter) {
     case 'a': return 1;
     case 'b': return 3;
     case 'c': return 3;
     ...
     case 'z': return 10;
     default: return 0;
   }
 }

Example Magic Number Refactor:

/** In this example, 7 is used as the max password size. To avoid having
 * to sprinkle the value 7 all over the code, MAX_PASSWORD_SIZE is used
 * instead, which makes more sense. If the max password size needs to be
 * changed, the value is updated everywhere MAX_PASSWORD_SIZE is used.
 * */
public class Foo {
   public void setPassword(String password) {
        // don't do this
        if (password.length() > 7) {
             System.out.println(“Password is too long!”);
        }
   }
}
//This should be refactored to:
public class Foo {
   public static final int MAX_PASSWORD_SIZE = 7;
 
   public void setPassword(String password) {
        if (password.length() > MAX_PASSWORD_SIZE) {
             System.out.println(“Password is too long!”);
        }
   }
}

Example Line Wrapping Style

//Example 1: calling a method
someMethod(longExpression1, longExpression2, longExpression3, 
       longExpression4, longExpression5);
 
//Example 2: math expression
longName1 = longName2 * (longName3 + longName4 - longName5)
          + 4 * longname6;
 
//Example 3: method header
int someMethod(int anArg, Object anotherArg, String yetAnotherArg,
          Object andStillAnother) {
   ...
}
 
//Example 4: method header with a lot of arguments
private static synchronized horkingLongMethodName(int anArg,
       Object anotherArg, String yetAnotherArg,
       Object andStillAnother) {
   ...
}
 
//Example 5: conditional statements
if ((condition1 && condition2)
       || (condition3 && condition4)
       ||!(condition5 && condition6)) {
   doSomethingAboutIt();
} 
 
//THIS COULD ALSO WORK
if ((condition1 && condition2) || (condition3 && condition4)
       ||!(condition5 && condition6)) {
   doSomethingAboutIt();
} 

If you’re curious, more coding style guides can be found on the Oracle website. Google also has a great style guide for Java which we'll accept for this course: https://google.github.io/styleguide/javaguide.html