Java Reference
In-Depth Information
the cases that we expect for this method, but that isn't good enough. Java insists that
we cover every possible case.
Understanding this idea can simplify the code you write. If you think in terms of
paths and cases, you can often eliminate unnecessary code. For our method, if we
really want to return just one of three different values, then we don't need a third test.
We can make the final branch of the nested if/else be a simple else :
public static String rating(int totalSAT) {
if (totalSAT >= 600 && totalSAT < 1200) {
return "not competitive";
} else if (totalSAT >= 1200 && totalSAT < 1800) {
return "competitive";
} else { // totalSAT >= 1800
return "highly competitive";
}
}
This version of the method compiles and returns the appropriate string for each
different case. We were able to eliminate the final test because we know that we want
only three paths through the method. Once we have specified two of the paths, then
everything else must be part of the third path.
We can carry this idea one step further. We've written a method that compiles and
computes the right answer, but we can make it even simpler. Consider the first test, for
example. Why should we test for the total being greater than or equal to 600? If we
expect that it will always be in the range of 600 to 2400, then we can simply test
whether the total is less than 1200. Similarly, to test for the highly competitive range,
we can simply test whether the score is at least 1800. Of the three ranges, these are the
two simplest to test for. So we can simplify this method even further by including tests
for the first and third subranges and assume that all other totals are in the middle range:
public static String rating(int totalSAT) {
if (totalSAT < 1200) {
return "not competitive";
} else if (totalSAT >= 1800) {
return "highly competitive";
} else { // 1200 <= totalSAT < 1800
return "competitive";
}
}
Whenever you write a method like this, you should think about the different cases
and figure out which ones are the simplest to test for. This will allow you to avoid writ-
ing an explicit test for the most complex case. As in these examples, it is a good idea to
include a comment on the final else branch to describe that particular case in English.
Search WWH ::




Custom Search