Java: '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
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
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 much more
readable programs:
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);
Complaint
Some programming languages recognize this as a common kind
structured-programming construction, and have a special
'elseif' statement. This would be a nice thing to add
to Java.