Is Switch (Case) always wrong?

2020-02-12 03:03发布

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

8条回答
Luminary・发光体
2楼-- · 2020-02-12 03:28

My view is that switch is always wrong:

The body of a case is code and is behaviour, therefore, the thing in the case (the 'value') has a behavioural type, therefore, polymorphism would be a better choice.

This implies that values are in fact types, e.g. the number 1 is a type of everything that equals 1 in some way. All that remains is for us to map 1-ness to the behaviour for our specific case, and we have polymorphism with all those other types (a Good Thing).

This is easier done in some languages than others, unfortunately, most languages in common use are pretty awful, so the path of least resistance is the wrong one, and people end up writing switches or if statements (same thing).

查看更多
走好不送
3楼-- · 2020-02-12 03:29

it's usually ok, as long as you only have one switch in one place. when you have more than one (or many), then it's time too consider alternatives.

查看更多
登录 后发表回答