Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should we always favor polymorphism over enums?

Tags:

After watching: The Clean Code Talks -- Inheritance, Polymorphism, & Testing

I checked my code and noticed a few switch statements can be refactored into polymorphism, but I also noticed I only used switch statements with enums. Does this mean enums are "evil" in OO-design and should be eliminated with polymorphism?

like image 912
Pyrolistical Avatar asked Dec 19 '08 19:12

Pyrolistical


1 Answers

It's not that enums are evil, it's switch statements. There's a long discussion of this in the C++ FAQ Book, but the gist is this: except for limited areas --- for example the interpretation of data coming in from a register on a device --- a big switch comb suggests that you're using data to distinguish among subtypes. In place of that, you ought to just use subtypes, gaining the compiler's help in keeping it correct, and also meaning the compiler will automatically add new cases when you (inevitably) change the set of cases.

like image 90
Charlie Martin Avatar answered Oct 13 '22 04:10

Charlie Martin