Friday, April 1, 2011

Code Complete by Steve McConnell : Chapter 10

The author discusses points in using variables in this chapter:

  • Limit the scope of a variable as much as possible.
  • Keep references of a variable together
  • Initialize a variable as close to its use
  • Don't assign value to a variable until just before the value is used
The author advises to check that the programmer is not using a variable whose life span is already over and the value is stale. The author recommends binding of value to a variable as late as possible. The author provides example of binding a variable's value at compile time and run time.

The author then discusses a British computer scientist Michael Jackson's structured programming method which develops a general relationship between data structures and control structures.
The author suggests to use each temporary variable for only one purpose and avoid names like temp for a variable. The author suggests avoiding use of same variable to store values and using special values for error.
There shouldn't be unreferenced/unused variables in the code.
The author then provides list of problems in using global variables:
  • Use of global variables is against principle of information hiding.
  • Use of global variables increases the risk of side-effects.
  • Global variables increases the risk of aliasing, i.e. referring to the same variable with two different names.
  • Re-entrant code will not work correctly with global variables.
  • Global data limits the scope of code reuse.
  • Global data damages modularity and intellectual manageability.
The author then provides some valid reasons for usage of global data.
The author then provides some guidelines to reduce the risk of using global data:
  • Use naming convention to differentiate global variables.
  • Use locking to control access to global variables.
The author then provides a list of benefits to use access routines for global data:
  • The implementation of global data remains hidden from the rest of the program and can be changed when required without impacting the rest of the program.
The author then provides some rules on how to use access routines for global data.

No comments:

Post a Comment