Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
174 C++ Coding Standards 90. Avoid type switching; prefer polymorphism. Summary Switch off: Avoid switching on the type of an object to customize behavior. Use tem- plates and virtual functions to let types (not their calling code) decide their behavior. Discussion 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 fea- tures. 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 true--oftentimes, in addition to writing new code, we need to go back and modify some existing code. Changing working code is undesirable and should be minimized, however, for two reasons: First, it might break existing functionality. Second, it doesn't scale well as the system