Why is this switch on type case considered confusing?

前端 未结 2 1964
鱼传尺愫
鱼传尺愫 2020-11-30 15:45

I was looking for a way to refactor and simplify one function where I have to do data sorting depending on input class type, and got stuck at switch(input.GetType()):<

相关标签:
2条回答
  • 2020-11-30 16:06

    It seems you don't expect the switch to match on subclasses. But this would break the Liskov Substitution Principle. (where if you passed in a C object, the code would work, but not with a D, even though D is a subclass of C).

    0 讨论(0)
  • 2020-11-30 16:12

    I think it's a perfectly valid argument on Peter Hallam's blog post that you don't expect switch statement to differ if you reorder things, so it's really only useful if only one branch can be valid at the same time, whereas with Type one class is always multiple different types along the inheritance chain.

    No one stops you from doing this with an if...else chain, where you do expect it to be evaluated in the order you put things.

    0 讨论(0)
提交回复
热议问题