TITLE: Are switch statements bad in OO design? RESPONSE: rmartin@rcmcon.com (Robert Martin), 15 Feb 94 There is nothing intrinsically evil about 'switch' statements. However they sometimes result from improper OO design. There are two design principles to keep in mind. 1. The open/closed principle: which states that each module should be open for extension but closed to modification. This means that you should be able to extend the function of a module by using derivation, rather than by changing any code in the modules itself. If your switch statement is checking the type of subclasses, then it cannot be closed against the addition of new subclasses. 2. Abstract modules should not depend upon their details. Details (derived classes) should depend upon abstractions (base classes). If your switch statement is setting high level policy, but is depending upon details, then the switch statement cannot be reused in a different context. If these two principles aren't violated by the switch statement, then you probably don't have a problem. I use the following rule of thumb. Switch statements can be used to create objects; usually based upon user input. Thus the body of a case should contain nothing but a constructor for the appropriate derived class. Moreover the switch statement should exist in a detailed module which is hidden behind an abstract interface: class Transaction; class BuyTransaction : public Transaction {...}; class SellTransaction : public Transaction {...}; class TransactionSelector { public: virtual Transaction* Select() = 0; }; class KeystrokeTransactionSelector : public TransactionSelector { public: virtual Transaction* Select(); }; Transaction* KeystrokeTransactionSelector::Select() { char c; cin >> c; Transaction* retval = 0; switch (c) { case 'b': retval = new BuyTransaction; break; cast 's': retval = new SellTransaction; break; } return retval; }