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;  }
Share the Post:
data observability

Data Observability Explained

Data is the lifeblood of any successful business, as it is the driving force behind critical decision-making, insight generation, and strategic development. However, due to its intricate nature, ensuring the

Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved