next up previous
Next: Week 4 Up: Week 3 Previous: The String Class


Comments and Understandability: Dearth of Obfuscation

Java code is not something that most people feel curling up with at bedtime. That's not to say that it's not interesting, but it doesn't exactly have the same communicative ability as English or other natural languages. This can be a problem if you write some code and then come back to it a year later, or if you hope for someone else to understand the code that you've written. Even the title to this section might not be particularly clear; notice that we always have choices we make in the words use. Simple and direct is usually better.

There are a few things that you can do to make your code more understandable:

  1. Try to choose names for variables, classes, and methods that convey to the reader function or meaning
  2. Don't sacrifice readability in order to cram more code on a line
  3. Comment your code

What are comments? These are English sentences that we can add to our code in order to make it more understandable. Of course the compiler can't understand English sentences, so what we have to do is to use some special constructions to tell the compiler: ``Ignore the stuff here - it's not in your language!''.

There are three such constructions in Java:

  1. // : The rest of this line is English
  2. /* All the stuff in the middle is English */
  3. /** Same as above, except javadoc processes these comments... */

The first construction allows you to write comments on a single line. The second and third constructions can span several lines; the third construction is suitable if you intend to use the program javadoc to create formatted html documentation out of the comments you write. This is a fairly simple program, and we won't discuss it, but there is adequate information about it on the web if you're interested.

What should you put in the comments?

The following guidelines are reasonable:

  1. At the beginning of every method, describe what the method does, what it's parameters are for and what its return value is
  2. At the top of every class, describe what data the class is intended to describe and what methods it offers
  3. At each variable declaration, describe the purpose of the variable
  4. Throughout a method sprinkle comments to describe what is happening

An example will appear soon....


next up previous
Next: Week 4 Up: Week 3 Previous: The String Class
Chris Trendall
Copyright ©Chris Trendall, 2001. All rights reserved.

2001-12-09