Best Practices: Variables

Notes from Code Complete 2: Chapter 10

Date Types

  • Know your data types (10.1)

Declaration and Naming

  • Declare all variables (turn off implicit declarations) (10.2)
  • Follow naming conventions (10.2)

Initialization

  • Initialize each variable as it’s declared (10.3)
  • Declare and define each variable close to where it’s first used (10.3)
  • Initialize working memory at the beginning of your program
  • Use the compiler setting that automatically initializes all variables
  • Initialize a class’s member data in its constructor
  • Pay special attention to counters and accumulators – ensure that they are initialized properly and, if necessary, reinitialized each time they are used
  • Check the need for reinitialization
  • Check that variables are reinitialized properly in code that’s executed repeatedly
  • Initialize named constants once; initialize variables with executable code
  • Check input parameters for validity
  • Use a memory-access checker to check for bad pointers
  • Don’t assign a value to a variable until just before the value is used
  • Use final or const when possible
  • Use named constants (avoid magic numbers)
  • Strike a conscious balance between the flexibility of late binding and the increased complexity associated with late binding

Scope

  • Ensure that variables have the smallest scope possible
  • Develop the habit of declaring and initializing all data right before it’s used
  • Localize References to Variables
  • Keep Variables “Live” for as Short a Time as Possible
  • Initialize variables used in a loop immediately before the loop rather than back at the beginning of the routine containing the loop
  • Group related statements
  • Break groups of related statements into separate routines
  • Begin with most restricted visibility, and expand the variable’s scope only if necessary

Purpose

  • Use each variable for one purpose only
  • Avoid variables with hidden meanings
  • Make sure that all declared variables are used

Persistence

  • Write code that assumes data isn’t persistent (10.5)

Release

  • Set variables to “unreasonable values” when you’re through with them (10.6)

General

  • Enable and pay attention to compiler warnings