CS 200 Style Guide

Examples: Frame.java, Circle.java

The CS200 Java Style settings XML file for Eclipse is: CS200Style.xml.
(This is copied and slightly modified from the style file at https://github.com/google/styleguide)
To see how to make the CS200 Java Style the default formatter in Eclipse, go to Configure Style and Encoding.

0. Introduction

Good programming style isn’t meant for the compiler, which only requires that you use the correct syntax for the programming language. Programmers use good programming style to ensure that their source code is easily read and understood by people. Good style will also help you develop your code more efficiently and minimize bugs.

A programmer’s personal style develops over their career, but there are many occasions in which a programmer must adapt their personal style to conform with the style guide of a particular project.  This CS 200 Style Guide is heavily influenced by the Google Java Style Guide, and has been designed to help you develop good habits along with your own personal style.  It is organized into the following general sections:

1. Source Files

File Name

The source file name consists of the case-sensitive name of the top-level class it contains (of which there is exactly one), plus the .java extension.

File Encoding: UTF-8

Source files are encoded in UTF-8.

File Organization

Each source file consists of, in order:

  • A file header comment in exactly the following form:
///////////////////////// TOP OF FILE COMMENT BLOCK ////////////////////////////
//
// Title:           descriptive title of the program making use of this file
// Course:          course number, term, and year
//
// Author:          your name
// Email:           your @wisc.edu email address
// Lecturer's Name: name of your lecturer
//
///////////////////////////////// CITATIONS ////////////////////////////////////
//
// https://cs200-www.cs.wisc.edu/wp/syllabus/#academicintegrity
// Source or Recipient; Description
// Examples:
// Jane Doe; helped me with for loop in reverse method
// https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html; 
//         counting for loop
// John Doe; I helped with switch statement in main method.
//
/////////////////////////////// 80 COLUMNS WIDE ////////////////////////////////
  • All import statements (if any are needed).  Wildcard imports are not used.
  • Exactly one top-level class (with appropriate javadoc documentation).  The contents of this class may be ordered in a logical fashion of your choosing.

… with exactly one blank line separating each section that is present.

2. Formatting

2.1. Spacing

Whitespace Characters

Aside from the line terminator sequence, the ASCII horizontal space character (0x20) is the only whitespace character that appears anywhere in a source file. This implies that:

  • All other whitespace characters in string and character literals are escaped.
  • Tab characters are NOT used for indentation.

Horizontal Whitespace

A single blank space appears:

  • Separating curly braces from any other code on the same line.
  • On both sides of a binary or ternary operator or operator like symbol, with the exception of the dot opertor which should instead be written without spaces as: object.toString()
  • On both sides of the double slash // comments
  • Between the type and name of variable declarations, as in: List<String> list;
  • After each coma in coma separated lists of arguments and initializes
  • And anywhere else they help improve the readability of your code

Block Indentation: +4 spaces

Each time a new block or block-like construct is opened, the indent increases by four spaces.  When it ends, the indent returns to the previous indent level.  This indent level applies to both code and comments throughout the block.

Column Limit: 100

No line of code should extend beyond 100 characters wide.  Any line that would exceed this limit must be line-wrapped as described below.

Line Wrapping

Prefer breaking lines apart at the highest syntactic level, to conform to the Column Limit (above) or otherwise improve the readability of your code.  Here are some suggests for

  • When a line is broken near an operator, the break should generally come before the operator (although many people do prefer breaking after assignment operators).
  • Method and constructor names should stay attached to their following open parenthesis.
  • Commas should stay attached to the token that precedes them.
  • Long string constants can be split across multiple lines using the concatenation operator (+).

Indent continuation lines at least +6 spaces from the first line that they are extending, so that all continuation lines are indented the same amount.

One Statement per Line

Each statement should be on it’s own line.  Some effort should be made to decompose overly complex statements into several simpler statements.

Vertical Whitespace

A single blank line appears:

  • between consecutive class members, although the line between consecutive private fields is optional.
  • between consecutive statements when that helps group logical subsections of the code.

Switch Statements

The body of a switch statement should be indented +4 spaces like any other code block.  Each case (or group of cases) are followed by a statement group that should also be indented +4 spaces as if they were also statement blocks.  Here’s an example:

switch (input) {
    case 1:
    case 2:
        prepareOneOrTwo();
        // fall through
    case 3:
        handleOneTwoOrThree();
        break;
    default:
        handleLargeNumber(input);
}

2.2. Braces and Parentheses

Alignment of Braces

For all non-empty blocks or block-like structures surrounded by braces:

  • Either 1) include a line break before the opening brace (Allman or “BSD” style), or 2) exclude any line breaks before the opening brace (K&R or “Egyptian” style).  Be consistent in this choice throughout your code.
  • Include a line break after the opening brace.
  • Include a line break before the closing brace.
  • Include a line break after the closing brace, unless it is followed by an else or a coma.

Examples:

return () -> {
    while(condition()) {
        method();
    }
};

return new MyClass() {
    @Override public void method() {
        if(condition()) {
            try {
                something();
            } catch (ProblemException e) {
                recover();
            }
        } else if(otherCondition()) {
            somethingElse();
        } else {
            lastThing();
        }
    }
};

Grouping Parentheses

It’s not reasonable to expect that every reader has memorized the entire Java operator precedence table.  Use optional grouping parentheses to prevent any doubt or confusion that you could imagine the readers of your code encountering.

3. Naming

Common Identifier Rules

Identifiers use only ASCII letters and digits, and underscores in a some constants (as noted below). Thus each valid identifier name is matched by the regular expression \w+.

Class and Interface Names

Class and Interface names are written in UpperCamelCase. Class names are typically nouns or noun phrases. For example, Character or ImmutableList. Interface names may also be nouns or noun phrases (for example, List), but may sometimes be adjectives or adjective phrases instead (for example, Readable).

Method, Field, and Local variable Names

Methods, fields and local variable names are written in lowerCamelCase. Method names are typically verbs or verb phrases. For example, sendMessage or stop.  Field and local variable names are typically noun or noun phrases.  Note that constant fields and local variables present an exception to this rule that is described below.

Constant names

Constant names use CONSTANT_CASE: all uppercase letters, with words separated by underscores. But what is a constant, exactly?

Constants are static final fields whose contents are deeply immutable and whose methods have no detectable side effects. This includes primitives, Strings, immutable types, and immutable collections of immutable types. If any of the instance’s observable state can change, it is not a constant. Merely intending to never mutate the object is not enough.

4. Commenting

Inline Comments

Inline comments are indented to the same level as the surrounding code. They may be in /* … */ style or // … style. For multi-line /* … */ comments, subsequent lines must start with * aligned with the * on the previous line.

/*
 * This is
 * okay.
 */

// And so
// is this

Use comments within the body of methods to:

  • highlight lines of code that are counter-convention or still work-in-progress
  • explain long calculations or conditions tied to unobvious state
  • clarify convoluted or unusual code
  • mark locations where you suspect a bug may exist
  • mark locations where improvements or enhancements are planned

Do not use comments in methods to explain things that are obvious to most programmers.  For example, it is not useful to provide comments such as “this assignment statement assigns 22 to the variable x”. Instead use comments to point out things that are not immediately evident, or to help contextualize sections of code.

JavaDoc

The basic formatting of Javadoc style comments that are used by many developer tools is demonstrated in the following example.  Notice that paragraphs are separated by a single line of comment that includes only the html new paragraph opening tag: <p>.

/**
 * Multiple lines of Javadoc text are written here,
 * wrapped normally...
 * <p>
 * This is the start of a new paragraph!
 */
public int method(String p1) { ... }

… or in this single-line example:

/** An especially short bit of Javadoc. */

Block tags

Any of the standard “block tags” that are used appear in the order @param, @return, @throws, @deprecated, and these four types never appear with an empty description. When a block tag doesn’t fit on a single line, continuation lines are indented four (or more) spaces from the position of the @.

7.3 Where Javadoc is used

A Javadoc comment MUST be present for every class, and for every method within each of those classes.

  • For CS 200, in the paragraph following the basic method description, highlight the major steps of the algorithm used in the method.

5. Miscellaneous

Numeric Literals

long-valued literals use an uppercase L suffix to avoid confusion between the lower case letter ‘l’ and the number ‘1’.  For example, use 3000000000L rather than 3000000000l.

Variable Declarations

Every variable declaration (field or local) statement declares only one variable.  Do NOT use declarations like: int a, b;.  Variable declarations are NOT required to be grouped at the start of their containing block, although this style is permitted.  Once declared, variables should generally be initialized as soon as possible.

Avoid C-Style Array Declarations

The square brackets form a part of the type, and not the variable.  For example use: String[] args, instead of String args[].

Modifier Ordering

Class and member modifiers, when present, should appear in the order recommended by the Java language specification: public protected private abstract default static final transient volatile synchronized native strictfp

Use @Override

The @Override annotation should be included whenever it is legal to do so.

Static Members Qualification

When a reference to a static class member must be qualified, it is qualified with that class’s name, and NOT with a reference to an object of that class’s type.