next up previous
Next: Testing:If I Write It Up: Program Correctness Previous: Program Correctness

Style: How Can I Write It? Let Me Count The Ways....

The goal of the guidelines in this section is to make programs more understandable. There are a number of different ways in which we can write a program which accomplishes a certain task; what we want to do is to choose the way that will be easiest for us to understand, debug, and modify. We'll use the word style to refer to 'what the program looks like' (as opposed to 'how the program works').

What are the things that we can change that have no effect on 'how the program works'?

  1. Variable Names
    1. i,j,k are common names for indices in loops. Otherwise, choose informative names.
    2. Don't choose informative names which are too long, otherwise code looks 'messy'.
    3. When we put comments in a program, we want to put a comment which describes the 'meaning' or 'use' of a variable above, beside, or below each variable declaration. Therefore, a general guideline for the length of an informative variable name is: if the variable is used 'far' from its declaration, you can use a longer name. This is because when we use the variable close to the declaration, we can easily look at the comment we wrote describing its meaning. When we are reading code where the variable is used and it's farther from the declaration, it's more difficult to find the declaration and the comment, so more information about the variable should be contained in its name.

  2. Constants
    1. Declare values that are shared throughout the code but don't change using the final keyword: public static final int MAX_STUDENTS = 1000;
    2. final means that your program can't change the value: it's a constant.
    3. I like to use capital letters for constant variable names to remind myself that it's a constant.

  3. Horizontal Spacing
    1. Use indentation to indicate the body of a method, the body of a loop, the body of an if-else statement and so on.
    2. Line up the closing brace } with the beginning of the line on which the opening brace { appears.
    3. If a statement is too long for a line and has to continue on the next line, indent it more.
    4. See code example in previous sections for examples

  4. Vertical Spacing
    1. Use blank lines to separate chunks of code that should go together
    2. e.g. class definitions should be separated, method definitions within a class should be separated, loops, or lines of code that are strongly inter-related should also be separated from other lines of code.

  5. Comments
    1. see section on Comments and Understandability


next up previous
Next: Testing:If I Write It Up: Program Correctness Previous: Program Correctness
Chris Trendall
Copyright ©Chris Trendall, 2001. All rights reserved.

2001-12-09