6.170 / Spring 2004 / Java Style Guide

Handout S1

Contents:


Overview

Coding style is an important part of good software engineering practice. The goal is to write code that is clear and easy to understand, reducing the effort required to make future extensions or modifications.

In 6.170 we do not specify a detailed coding style that you must follow. However we expect your code to be clear and easy to understand. This handout provides overall guidelines within which you should develop your own effective coding style.


Descriptive names

Names for packages, types, variables, and branch labels should document their meaning and/or use. This does not mean that names need to be very long. For example, names like i and j are fine for indexes in short loops, since programmers understand the meanings and uses of these variables by convention.

You should follow the standard Java convention of capitalizing names of classes, but starting method, field, variable, and package names with a lower case letter. Constants are named using all uppercase letters. The Java Language Specification provides some common Naming Conventions that you may want to use when naming your classes, methods, etc.


Consistent indentation and spacing

Indenting code consistently makes it easy to see where if statements and while loops end, etc. You should choose consistent strategies; for example, be consistent about whether you put the open curly brace on the same line as the if or on the next line, or what your try-catch-finally blocks looks like. Examine the code in the textbook for a sample style; feel free to develop your own if it makes you more comfortable.

In Emacs's Java mode, return indents the next line to (its guess at) the correct column, and the tab key re-indents the current line. There are also commands for re-indenting an entire region of lines.

Consistent (and adequate) spacing also helps the reader. There is no reason to try to jam your code into as few columns as possible. You should leave a space after the comma that separates method arguments. You should leave a space between for, if, or while and the following open parenthesis; otherwise, the statement looks too much like a method call, which is confusing. In general, you should place only one statement on each line.


Informative comments

Don't make the mistake of writing comments everywhere -- a bad or useless comment is worse than no comment. If information is obvious from the code, adding a comment merely creates extra work for the reader. For example, this is a useless comment:
    i++;    // increment
Good comments add information to the code in a concise and clear way. For example, comments are informative if they: Hints:

Back to the 6.170 home page.
For problems or questions regarding this page, contact: 6.170-webmaster@mit.edu.