devxlogo

Switch Statements in Object Oriented Design

Switch Statements in Object Oriented Design

There is nothing intrinsically evil about ‘switch’ statements. However, they do sometimes result from improper Object Oriented design. There are twodesign principles to keep in mind.
1. Open/Closed Principle: this states that each module shall be open for extension but closed for modification.
2. Abstract modules should not depend on their details. Details (derived classes) should depend upon abstractions (base classes).
If the switch statement doesn’t violate these two principles, then you probably don’t have a problem.
Switch statements can be used to create objects; usually based upon user input. The body of a case should contain nothing but a constructor for the appropriate derived class. The switch statement should exist in a detailed module that is hidden behind an abstract interface. For example:

   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;  }

devx-admin

Share the Post: