Is Switch (Case) always wrong?

后端 未结 8 832
情歌与酒
情歌与酒 2020-12-19 00:37

Are there instances where switch(case) is is a good design choice (except for simplicity) over strategy or similar patterns...

8条回答
  •  暖寄归人
    2020-12-19 00:54

    Use Switches when you're testing on values of primitives. (ie. integers or characters).

    Use polymorphism when you are choosing between different types.

    Examples : Testing whether a character the user has entered is one of 'a', 'b' or 'c' is a job for a switch.

    Testing whether the object you're dealing with is a Dog or Cat is a job for polymorphic dispatch.

    In many languages, if you have more complicated values you may not be able to use Switch anyway.

提交回复
热议问题