6.170 / Spring 2001 / 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.

Many aspects of code help make it readable. Some of the most important are descriptive names, consistent indentation, and informative comments.

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.

A common convention that we recommend you follow is to capitalize names of classes, but start variable and package names with a lower case letter. There are other common conventions, such as naming constants using all uppercase letters; we do not require you to follow any particular conventions, but you should choose those that you find helpful and follow them consistently.


Consistent indentation

Indenting code consistently helps the reader understand the logical structure of your code by making 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.

Emacs provides an autoindent mode. You should use it to format your code as you type it, and reformat it after you have changed it. You can also use grind to format your code nicely for printing even if the source file is not well indented.


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.
    i++;    // increment i     THIS IS A USELESS COMMENT
Good comments add information to the code in a concise and clear way. For example, comments are informative if they: Hints:


Back to Supplemental Info.
Back to the 6.170 home page.
For problems or questions regarding this page, contact: 6.170-webmaster@mit.edu.
$Id: javastyleguide.html,v 1.1 2001/02/22 16:29:21 kenlu Exp $