Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: Intermediate
Apr 5, 2002



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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 two design 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
      virtual Transaction* Select() = 0;

  class KeystrokeTransactionSelector : public TransactionSelector
      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;
Sriram Swaminathan
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



Thanks for your registration, follow us on our social networks to keep up-to-date