CPSC 124 Introduction to Programming Spring 2023

Good Programming Style

Programs are written for people just as much as they are written for computers - by far the longest part of the life of real software is the maintenance phase, where programmers may go back for years to fix bugs and add features. It is thus important to make sure they can understand the program.

Having good programming style is also valuable for your own sake - a clear and well-organized program will help your thought processes as you develop the program and will make it easier to find bugs.

Any program that you turn in for this course should obey the rules of good programming style. You will be graded on your programming style, and will lose points for poor style. You can use the programs in the book and those from class (posted on the schedule page) as examples to emulate.

So what is good programming style? The following rules are already relevant:

Additional rules will be added throughout the course (and can be found in the course programming standards).

A note on commenting: Don't use comments to explain how Java works. Assume that anyone reading a Java source code file knows Java. Instead, include important information that can't be obtained from the code itself.

For example, the following is a useless comment:

  double interestRate;  // declare a variable named interestRate

It is useless because it repeats exactly what the statement double interestRate; means - someone familiar with Java already knows that is a declaration for a variable named interestRate. The comment doesn't tell the reader anything new.

The following is a better comment:

  double interestRate;  // declare a variable to hold the annual interest rate

This communicates the purpose of the variable - to hold the interest rate - and provides some important information not apparent from the variable name - that the interest is an annual interest rate, rather than a daily or monthly one. However, it is unnecessarily wordy - there's no need to say "declare a variable to hold" because we can recognize double interestRate; as a variable declaration and that's exactly what a variable declaration does.

The following is the best comment:

  double interestRate;  // annual interest rate (0-1)

This communicates the purpose of the variable - to hold the interest rate - and provides two pieces of important information not apparent from the variable declaration itself: that this is an annual interest rate (not daily or monthly), and that percentages should be expressed as a decimal between 0 and 1 instead of between 0 and 100. (i.e. 12.5% should be stored as 0.125)