Beauty is more important in computing than anywhere else in technology because software is so complicated. Beauty is the ultimate defense against complexity.
Good programmers know what's beautiful and bad ones don't.
-- David Gelernter, Machine BeautyProgramming is best regarded as the process of creating works of literature, which are meant to be read.
-- Donald Knuth, Literate ProgrammingThe rules and guidelines on this page are generally consistent with the much more detailed rules used by Sun Microsystems (the designer and maintainer of Java), which they recommend for all Java programmers.
Always obey the rules, prefixed below by R. There will be a significant grade penalty for breaking them. Like grammatical mistakes in English, if you break the rules it is quite distracting, and may cause serious confusion for your reader.
Guidelines, prefixed below by G, should be generally followed or your program becomes hard to read, but violations are not as serious as breaking rules, and exceptions are sometimes appropriate.
Avoid dead code that can never be reached due to local program structure. This most commonly results from including an else clause after a series of else ifs that exhaust all possibilities. Instead, delete the last if (which would surely be true) and replace it with a comment indicating the condition.
Wrong:
if (x <= y) {
doThis();
}
else if (x > y) {
doThat();
}
else impossible();
Ok:
if (x <= y) {
doThis();
}
else { // x > y
doThat();
}
It is still a good idea to detect and report errors that
might result from errors in other parts of a program or invalid input
resulting in data structures or other forms of program state that are
inconsistent with the program design.Thus if local logic analysis does
not prove that data is in the expected form in an else clause (or switch
default clause), the clause should be replaced by an if statement that
tests for the expected form and has an else clause that raises an
exception.
Wrong:
if (x == 1) one();
else {
if (x == 2) two();
else moreThanTwo();
}
Also wrong:
if (x == 1) one();
else if (x == 2) two();
else moreThanTwo();
Ok:
if (x == 1) one(); else if (x == 2) two(); else moreThanTwo();