Java Reference
In-Depth Information
comparisons such as < and <= . Check that the loop is not traversed at all, or only
once, and that the final result is what you expect.
If you write a for loop, check to see whether your bounds should be symmetric or
asymmetric (see Quality Tip 6.3 ), and count the number of iterations (see Quality
Tip 6.4 ).
Q UALITY T IP 6.3: Symmetric and Asymmetric Bounds
It is easy to write a loop with i going from 1 to n :
for (i = 1; i <= n; i++) . . .
The values for i are bounded by the relation 1ʎ i ʎ n . Because there
areʎcomparisons on both bounds, the bounds are called symmetric.
When traversing the characters in a string, the bounds are asymmetric.
for (i = 0; i < str.length(); i++) . . .
The values for i are bounded by 0ʎ i < str.length() , with aʎcomparison
to the left and a < comparison to the right. That is appropriate, because
str.length() is not a valid position.
Make a choice between symmetric and asymmetric loop bounds.
It is not a good idea to force symmetry artificially:
for (i = 0; i <= str.length() - 1; i++) . . .
That is more difficult to read and understand.
For every loop, consider which form is most natural for the problem, and use that.
Q UALITY T IP 6.4: Count Iterations
Finding the correct lower and upper bounds for an iteration can be confusing.
Should I start at 0? Should I use <= b or < b as a termination condition?
Search WWH ::




Custom Search