October 2004
Intermediate to advanced
240 pages
6h 22m
English
Switch off: Avoid switching on the type of an object to customize behavior. Use templates and virtual functions to let types (not their calling code) decide their behavior.
Type switching to customize behavior is brittle, error-prone, unsafe, and a clear sign of attempting to write C or Fortran code in C++. It is a rigid technique that forces you to go back and do surgery on existing code whenever you want to add new features. It is also unsafe because the compiler will not tell you if you forget to modify all of the switches when you add a type.
Ideally, adding new features to a program equates to adding more new code (see Item 37). In reality, we know that that’s not always ...