[Home]
[Edit this page]
[Recent Changes]
[Special Pages]
[Help]
CppTypeSwitching
'Avoid type switching; prefer polymorphism' [1]
An example is the code below, followed by the equivalent classes using polymorphism.
The correct equivalent:
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
CppTypeSwitching
(C++) Type switching
Type switching means that in a class there is an internal variable stored to embody the type of the class. The a switch-statement is used to conclude its behaviour.'Avoid type switching; prefer polymorphism' [1]
An example is the code below, followed by the equivalent classes using polymorphism.
enum MyClassType { happy, sad, angry }; class MyClass { private: const MyClassType mType; public: MyClass(const MyClassType& state) : mType(state) { ; } void sayHello() const { switch (mType) { case happy : std::cout << "Hello!!!" << std::endl; break; case sad : std::cout << "... hello ..." << std::endl; break; case angry : std::cout << "HELLO!!!" << std::endl; break; default: assert(!"Unknown value of mType"); std::exit(1); } } }; int main() { std::vector<MyBaseClass* > myVector(3); myVector[0] = new MyClass(happy); myVector[1] = new MyClass(sad); myVector[2] = new MyClass(angry); const int size = myVector.size(); for (int i=0; i!=size; ++i) myVector[i]->sayHello(); //Clean up for (int i=0; i!=size; ++i) delete myVector[i]; }
- include <iostream>
- include <vector>
The correct equivalent:
struct MyBaseClass { virtual void sayHello() const = 0; }; struct MyHappyClass : public MyBaseClass { void sayHello() const { std::cout << "Hello!!!" << std::endl; } }; struct MySadClass : public MyBaseClass { void sayHello() const { std::cout << "... hello ..." << std::endl; } }; struct MyAngryClass : public MyBaseClass { void sayHello() const { std::cout << "HELLO!!!" << std::endl; } }; int main() { std::vector<MyBaseClass* > myVector(3); myVector[0] = new MyHappyClass; myVector[1] = new MySadClass; myVector[2] = new MyAngryClass; const int size = myVector.size(); for (int i=0; i!=size; ++i) myVector[i]->sayHello(); //Clean up for (int i=0; i!=size; ++i) delete myVector[i]; }
- include <iostream>
- include <vector>
Code links
- #include
- enum
- class
- private
- public
- iostream
- main
- std
- scope operator'::'
- cout
- stream out operator '<<'
- endl
- return
Reference
- 1) Herb Sutter and Andrei Alexandrescu. C++ coding standards: 101 rules, guidelines, and best practices. ISBN: 0-32-111358-6. Chapter 90: 'Avoid type switching; prefer polymorphism'.
[Edit this page] [Page history] [What links here] [Discuss this topic] [Printer Friendly]
