Programming in Style
This article is aimed at undergraduates who are learning to program.
This a introductory guide to good programming style for Java code. The main areas of concern about style are these (in no particular order):
Choosing good identifier names
An identifier is the name of something. It could be a variable, or the name of a user-defined type, or the name of a function or procedure. For example, the method signature
public String rainbowToString(RainbowColour col)
refers to several identifiers:
rainbowToString– the identifier giving the name of the methodcol– the identifier giving name of the parameter for the methodRainbowColour– this is the name of a user-defined type
There are two guidelines when choosing names for identifiers:
(1) Firstly, don’t choose a name that already exists in Java
(like for or while or interface)
because that just leads to confusion, even if you did manage to get
your code to compile.
(2) Secondly, although the names you choose don’t make any difference to a compiler, they matter a great deal when it comes to human beings reading the program. You should choose meaningful names for identifiers. Why? Because if someone else reads your program, then it is much easier to see the purpose of each variable, method and datatype/class.
You may think that nobody else will read your program, but a) it’s good to practice using good habits for when people do read your program, and b) even just a few weeks later you too can forget what the purpose of a variable is.
Examples of identifiers and commentary:
rainbowToString– this identifier suggest pretty strongly what this method does, converting from something of typeRainbowColourtoString. This is a good name.col– in this context, "col" is an abbreviation for colour, and is fairly meaningful, given the context above (it being of typeRainbowColour). If you wanted an even better one you could call itcolour, for example.RainbowColour– this is some kind of user-defined type/class for representing the seven colours of the rainbow, and as such,RainbowColouris an excellent name, very meaningful.- Suppose you wanted to represent the width and height of a box.
Then
boxWidthandboxHeightwould, for example, be good names. You might think that justwidthandheightwould be sufficient. So long as there weren’t other objects around also withwidthandheight, that would probably be sufficient, but if there’s any danger of it not being clear what it’s the width and height of, thenboxWidthandboxHeightwould be best.wandhalone would not be recommended, as they could stand for all sorts of things (week, weather, house etc.) - Sometimes there maybe isn’t an obvious name for a variable,
like when you just want an index variable to do a loop with.
In that sort of situation, a variable name like
i(for index) is fine, or if you’ve usedialready thenjandkare good standard ones to use too.
"Choose meaningful names" is something that sounds obvious, but there are many programs written where the programmers have not chosen meaningful names. Avoid being one of those programmers!
Commenting
Comments appear within the program code to document it (as opposed to external documentation, like software manuals). The idea is that comments are meant to be read by humans, not computers, so they are written with some kind of special marking to indicate to the compiler which text is part of the program code, and which text is a comment.
In Java (as in many other languages) comments are either
written just on one line, or in a block. For comments on one line,
you can use the // notation, where all text after the //
on the same line is ignored. For comments on several lines,
you can use the /* */ notation to begin and end comments.
To illustrate:
System.out.println("Hello..."); // This is a comment
/* This is a three-line comment
It will be ignored by the compiler. */
It’s important to put comments in your code so that other people and you (later, once you have forgotten what it was that you wrote and why you wrote it) can figure out what your program is up to. The best way to comment is to write comments as you program, not afterwards. When you are in the middle of programming some code, that’s when you know what the code is supposed to be doing, and that’s when it’s easiest to write the comments. If you leave it until later, then you just make it harder for yourself, so don’t do it.
Comments can be of various uses in a program. Here are some of the main uses:
Program headers
A header for the program, giving useful information, such as the date of the program, when the program was written, which version it is, what the program does. e.g.
/* Program with some library routines * for displaying price information neatly. * * Written by A. Programmer, November 2001 */
(Headers are usually more informative than that but that’s just to give you the idea!)
Describing procedures/functions
A comment should appear at the beginning of every non-constructor method in the program, describing what that method does. Sometimes just giving pre- and post-conditions are sufficient, sometimes a longer explanation might be required.
As for constructors, some constructor methods are simple and obvious enough not to need further explanation. But if the constructor is doing anything that isn't obvious at a casual glance, then it should be commented.
Consider
These comments are very useful for anyone looking at the code for this method. Looking at the comments, it’s clear that there are no restrictions for the use of the procedure (because the pre-condition is true) and the post-condition also clearly says what the procedure does. Ok this is a very short example where this information might be obvious just from looking at it, but imagine if the procedure was a lot more complicated than that, involving calling other procedures and with 100 lines of code used altogether – then it would not be so obvious!// pre: true // post: this robot is now facing the // opposite direction from before public void turn_around() { turn_right(); turn_right(); }Explaining difficult bits
Sometimes it is not obvious what a line or section of code does merely by looking at it, and a comment is really helpful. For example:
if ((year%4 = 0) && (not ((year%100 = 0) and ((year%400)!= 0)))) { // ie if the year is a leap yearMost people wouldn’t know for sure what the above means without that comment!
However please note that you don’t have to explain absolutely everything, only the difficult bits. In particular, don’t explain bits that are obvious to a fellow programmer. For example the following comment is unnecessary:
x++; // adds one to x
The above comment is unnecessary because a Java programmer will already know that doing
x++will add one tox.Commenting out code
Sometimes a comment can even contain a piece of program code. This typically happens if you’re trying out different versions of the code and you want to leave the old one hanging around in case it turns out to be useful later (or better than your other attempts!)
It’s important to get into the habit of commenting code as you write, and it’s easier to do it later on in your life when you need to (like for a professional programming job) if you are already in the habit of doing it anyway). Even in the short term, you’ll thank yourself for it when it comes to exam revision.
Program layout
There are two main issues to consider when you’re arranging your program code.
One is to do with the actual coding: how you group your code. Rather than having one long program with no procedures/functions in, it is much better style to organise your code so that it does use procedures and/or functions. Each procedure or function should have one clear specific purpose (if it does more than one thing, consider splitting it up into more procedures/functions).
The other issue is how you lay your program code out, and the most important aspect of this is indentation. Indentation refers to how much white space there is to the left of each line of code. For example, look at this code fragment without indentation:
i = 0;
while (i < n) {
j = 0;
while (j < i) {
if (a[j]>a[j+1])
swap(a[j],a[j+1]);
j = j+1;
}
i = i+1;
}
System.out.println("Finished now");
Some of those brackets match, but which is which? You have to try and peer closely to figure out which code belongs inside which loop. Now look at the same code properly indented:
i = 0;
while (i < n) {
j = 0;
while (j < i) {
if (a[j]>a[j+1])
swap(a[j],a[j+1]);
j = j+1;
}
i = i+1;
}
System.out.println("Finished now");
Now it’s a lot clearer which code belongs to which loop.
For example, you can easily see that all the code from
j = 0; to i = i+1; belongs to the outer
while loop.
So the purpose of indenting code properly is so that someone reading the program can easily tell which lines of code are inside which other bits. For good programming style you should do this too.
How to indent:
Step 1
Choose how many spaces you are going to use for one level of
indenting, and then stick consistently to that number.
3 or 4 are good numbers. 1 or 2 is too few, and more
than 4 will have your code flying to the right.
The example above uses 3 spaces.
Step 2
Make sure that the statements INSIDE a
loop/selection/method section are
indented by your chosen number of spaces.
After the section, the level of indentation
should go back to where it was before,
like in this style:
total = 0;
for (int i=1; i<=7; i++) {
System.out.println("i is "+i);
total = total + a[i];
}
System.out.println("Total is "+total);
It is recommended that you choose this style for indenting (different programming languages often have different indenting styles, but they all have the same basic features.
Going over this in more detail, a sequence of statements performed one after the other should be lined up, like this:
total = 0;for (int i=1; i<=7; i++) {System.out.println("i is "+i);total = total + a[i];}System.out.println("Total is "+total);
and also the beginning of a loop/selection statement should
match the end } of it, like this:
total = 0;for (int i=1; i<=7; i++) {System.out.println("i is "+i);total = total + a[i];}System.out.println("Total is "+total);Any statements after the (indented) body of a selection/loop statement should be back to the previous indenting level, like this:
total = 0;for (int i=1; i<=7; i++) {System.out.println("i is "+i);total = total + a[i];}System.out.println("Total is "+total);
Only the statements inside the { ... } get indented:
total = 0;for (int i=1; i<=7; i++) {System.out.println("i is "+i);total = total + a[i];}System.out.println("Total is "+total);If statements inside your loop body contain further nested statements, then you may find further levels of indentation, such as in this example:
i = 0;while (i < n) {
j = 0;
while (j < i) {
if (a[j]>a[j+1])
swap(a[j],a[j+1]);
j++;
};
i++;}System.out.println("Finished now");
Step 3
Practise indenting as you write your code, not afterwards.
It’s easy to forget to indent right as you write the code,
because you know at the time of writing which code belongs
to which bit. But when you come back to it after a few weeks,
or if someone else reads your code, then it won’t be so
clear any more. So indent as you write your code. Most development
environments will have features to help you get the indenting correctly
lined up.
