Tuesday, May 17, 2011

Code Complete by Steve McConnell : Chapter 15

The author discusses about loops in this chapter. The author provides different kinds of constructs available in different programming languages to implement looping. The author also provides examples where each kind of looping construct, loop with condition at the start, loop with condition at the end, loop with exit loop, for loop etc..., can be used.

The author suggests to minimize the number of factors that affect the loop and treat the inside of a loop as a routine.
The author then provides following guidelines for entering a loop:
  • Enter the loop from one location
  • Put initialization code just before the loop
The author also suggests following guidelines
  • Use infinite loop construct as per the language
  • Correctly choose whether to use while or for loop
  • Keep loop housekeeping scores at either the beginning or the end of the loop
  • Make each loop perform only one function
  • Don't play with the loop index for the loop to terminate
  • Avoid code that depends on loop index's final value
  • Make loop terminating condition obvious
  • Make sure the loop exits
  • Use safety counter that ensures exit from the loop
The author suggests that, for every loop, the programmer should check three cases of interest: the first case, an arbitrary middle case and the last case. The author then provides following guidelines for using loop variables:
  • Use ordinal or enumerated types instead of floats for limits on loops
  • Use meaningful variable names to make nested loops readable and avoid index cross-talk
  • Make loops short enough to view all at once
  • Limit loop nesting to three levels
  • Document long loops
The author then provides a way to easily write loops. Languages which do not provide operations on arrays, the author compares loops as single operations on a group of array elements.

No comments:

Post a Comment