Java Notes
'if' Statement - 'else if' style
Series of tests
It is common to make a series of tests on a value, where the
else
part contains only another if
statement.
If you use indentation for the else part, it isn't
easy to see that these are really a series of tests which
are similar. It is better to write them at the same indentation
level by writing the if
on the same line
as the else
.
Example -- series of tests - cascading ifs
This code is correctly indented, but ugly and hard to read. It also can go very far to the right if there are many tests.
if (score < 35) { g.setColor(Color.MAGENTA); } else { if (score < 50) { g.setColor(Color.RED); } else { if (score < 60) { g.setColor(Color.ORANGE); } else { if (score < 80) { g.setColor(Color.YELLOW); } else { g.setColor(Color.GREEN); } } } }
Example -- using 'else if' style for formatting
Here is the same example, using a style of writing the if
immediately after the else
. This is a common
exception to the indenting rules, because it results in more
readable programs. Note that it makes use of the rule that
a single statement in one of the Java clauses doesn't need
braces.
if (score < 35) { g.setColor(Color.MAGENTA); } else if (score < 50) { g.setColor(Color.RED); } else if (score < 60) { g.setColor(Color.ORANGE); } else if (score < 80) { g.setColor(Color.YELLOW); } else { g.setColor(Color.GREEN); }
Other languages
Some programming languages recognize this common construction with a special elseif keyword. Although it is hardly necessary, this kind of small touch can make a language a little nicer to use. The Java language designers are very conservative about adding keywords to the language, so don't expect it.