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

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist