Should we always favor polymorphism over enums?

前端 未结 6 640
北荒
北荒 2021-01-31 18:59

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

I checked my code and noticed a few switch statements can be refactored into polymorphis

6条回答
  •  情书的邮戳
    2021-01-31 19:36

    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.

提交回复
热议问题