It is important to develop a consistent and neat style for writing programs. It helps to avoid bugs, and it allows other people to read programs and give help more easily. In a team programming situation, it allows everyone to share development and maintenance of programs. These notes refer mainly to Java and C but most of the points also apply to other languages. Here are two sources of advice for programming style.
Horstmann's book, Appendix A1, available from the book's web page
Sun's style guide
Styles vary, but for this department, a particular style is encouraged and sometimes enforced. A style checker is provided for you to check your Java or C programs, and may be used in marking your assignments.
Style.class (download and run with java Style program.java)
style.html (a development report on the style checker)
Style.java (the source of the checker, for interest)
tests (the tests used on the checker; Allman.java illustrates the preferred style)
This style is designed to help you with difficult bugs that the compiler doesn't spot, to help lab supervisors or markers to scan your code quickly, and to allow various tools to be used to view or manipulate or analyse or print your code without problems. Here are the main points.
Lines < 80 characters long Long lines reduce readability, and as Sun points out, many tools only work properly with lines of < 80 characters. It is the maximum platform-independent width. Also, long lines annoy many people who use text windows 80 characters wide (so that two text windows fit comfortably side-by-side on the screen, e.g. to allow cut-and-paste from one to the other). Printouts wrap lines at 80 characters, which is not very readable; it is much better to decide logically where the split should be. Consider setting the fill column in your editor to 79, so that long comments, at least, stay inside the 80 character limit.
Last line ends in newline There is a standard convention on all platforms that every line of a text file, including the last, should have a newline at the end (\n or \r or \r\n, depending on the platform). Many tools rely on it. However, some text editors still allow you to create files with incomplete last lines. Customise your editor so it never happens, if possible. Here's some further notes on last lines.
No hard tabs Don't use tab characters in files because tab handling is not standardised across platforms or tools, printers don't deal with them properly, they make it harder to reformat or refactor code, and they go wrong when other people view your files. Set up your editor with soft tabs, so the tab character inserts spaces.
The only exception to the rule "never use tabs" is that, due to a horrible historical accident, the make program insists on them. Tabs are an example of hidden state; you can't see any difference between a tab and some spaces, and yet the difference matters. Tabs are obsolete; they were intended for compression, but compression does not matter for text files nowadays, and anyway it is much better done uniformly and transparently. A good example of bad use of tabs is the Sun Java sources which have an indent of 4, with hard tabs set at 8 spaces, so the files have a mixture of spaces and tabs. You can't reliably print or display or edit their files because the tabs don't look right unless you set tabbing to 8, but then that doesn't agree with their 4-space indent convention. Customize your editor to use soft tabs.
Suppose you have a favourite editor which doesn't support soft tabs, and you find hard tabs very convenient for development? Then you can create a shell script or batch file for running your editor which converts spaces into tabs before editing, and tabs back into spaces after editing. On Unix, the unexpand and expand commands can be used for this.
Narrow and neat indenting Use indents of 2, 3 or 4 spaces (pick one and stick to it). Anything more makes programs straggle to the right. Stick to some uniform convention for indenting and braces (curly brackets). The commonest conventions are pictured here (but see the style checker tests for more details):
Allman/BSD Horstmann GNU Whitesmiths K&R
if (b) if (b) if (b) if (b) if (b) {
{ { x = 1; { { x = 1;
x = 1; y = 2; x = 1; x = 1; y = 2;
y = 2; } y = 2; y = 2; }
} } }
Use one which suits you and your editor. The last one, the Kernighan-and-Ritchie style, is the original style from C and is still very popular, but it breaks Horstmann's really good "braces must line up" rule, so you should only use it if you are already incurably addicted to it. Of the others I would recommend the Allman style, also called BSD, especially if you want to customise emacs simply, the Horstmann style if you want to squeeze a lot of code into a small space (e.g. on lecture slides), and GNU or Whitesmiths if you use a folding editor.
If there is a single statement after an if or else, you can put it on the same line if you want:
if (n < 0) result = "negative"; else if (n > 0) result = "positive"; else result = "zero";
However, I suggest keeping to a "same-line-or-braces" rule. In other words, if there is a single statement, but it won't fit on the same line as the if or else, then use braces even though they are not strictly necessary. This is for ease of maintenance in case you want to add code, and to avoid the dangling else pitfall (see Horstmann, edition 3, page 208, though Horstmann doesn't always follow his own rule elsewhere in the book!). Customize your editor to set indents to 2, 3 or 4 spaces.
No mixed code and comments It is very tempting to put a comment at the end of a line of code, e.g.:
n++; // increment x
This is a bad idea for many reasons. First, such comments are often superfluous, just repeating something that is already well-explained by reading the code. Second, such comments are often an excuse for not making the code more readable. Third, these comments slow down your programming, and cost a lot of wasted effort to maintain, to keep them matching the code as the code is changed. (A programmer shouldn't be forever changing lines of code but, in real life, maintenance is common.) Fourth, these comments interrupt the flow of reading the code. Some people try to fix this by lining the comments up further to the right, out of the way, but this does not work well, because it causes another maintenance problem; as you change the code, you have to put a lot of wasted effort into re-aligning the comments. Fifth, these comments distract the programmer from the important job of adding more global comments about the overall design decisions being made, answering the question of why the program is written the way it is, not what the program actually does (which should be answered by the code itself). In textbooks, many authors use end-of-line comments to explain the code. This seems reasonable, but it isn't appropriate in real programs, it sets a bad example, and many programmers have picked up this bad habit from such authors.
Short methods Keep each method short enough so you can see the whole of it at once. Horstmann suggests a 30 line limit for Java. Long methods are a symptom of bad design and/or bad programming, and are difficult to read. The 30 line limit imposed by the checker excludes blank lines, comment lines, or lines containing only an open or close brace. This ensures that there is no incentive to leave out blank or comment lines, or to use one of the more compact indenting styles, just to squeeze inside the 30 line limit. Obviously, this is a rather crude and arbitrary restriction, and it can't force you to design well. However, it is a good rule for beginners to avoid developing bad habits, and it turns out to be surprisingly good for experts too, helping to improve their style and making it easier to debug or speed-read programs.
Readable methods Each method should be as readable as possible. It shouldn't be just a "lump of code", but should have a clear, self-contained purpose. It should have a one or two line comment before it to explain briefly what it does, but no comments inside it as a rule. Ideally, it should be possible to tell from reading the code itself how it works and whether it is correct. The comment should say what it does and how to use it. The method should not contain any "clever" (ie difficult to understand) code, or any code which is not directly relevant to what it is supposed to achieve. Good choices for variable names are much better than explanatory comments.
Spacing The way the code is spaced out on a line is not as important as bracketing and indenting etc, but there are some conventions. These are based on the conventions for punctuation etc in English:
= + - * / < ... one space
before, one space after, ; ) ] } no space before, one space
after( [ { one space before, no space
afterProgrammers are not very consistent about this, and common variations are:
no space before ( in function
declarations and/or function calls, no space before [ with arrays, no space after commas where the items
are simple variables or numbers rather than expressions, and no spaces either
side of arithmetic operators with simple arguments, e.g. x*y + z which makes the precedences clearer.