Should we always favor polymorphism over enums?

前端 未结 6 527
北荒
北荒 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:20

    I hesitate to call anything evil. It's a question of "How heavy do you want to engineer this".

    Enums/switches are fine - in some areas. Setting up a class hierarchy is overhead that isn't always needed for the problem. But the more code in the case statement, the more probable it is that, yeah, maybe you should be moving towards a heavier approach.

    My classic experience is a compiler I wrote for a class a few years ago. My roommate had the same class with me, and we approached it in two very different ways. I took a heavy-OO approach, full of polymophism. He took a heavy-C approach, using enums and unions. His code was ~1/2 the size of mine LOC-wise, his code was faster to compiler, and his code worked. His code was flexible, because it wasn't overengineered. That was a valuable lesson for me in software design.

提交回复
热议问题