switch 语句不好? [英] Switch statements are bad?

查看:31
本文介绍了switch 语句不好?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近了解到 switch 语句在 OOP 中很糟糕,特别是来自 Robert Martin 的Clean Code"(p37-39).

I recently learned that switch statements are bad in OOP, perticularly from "Clean Code"(p37-39) by Robert Martin.

但是考虑一下这个场景:我正在编写一个游戏服务器,接收来自客户端的消息,其中包含一个整数,表示玩家的动作,例如移动、攻击、拾取物品……等等,会有超过 30 种不同的行动.当我编写代码来处理这些消息时,无论我想到什么解决方案,它都必须在某个地方使用 switch.if not switch 语句应该使用什么模式?

But consider this scene: I'm writing a game server, receiving messages from clients, which contain an integer that indicates player's action, such as move, attack, pick item... etc, there will be more than 30 different actions. When I'm writing code to handle these messages, no metter what solutions I think about, it will have to use switch somewhere. What pattern should I use if not switch statement?

推荐答案

开关就像任何其他控制结构.有些地方它是最好/最干净的解决方案,还有更多地方完全不合适.它只是比其他控制结构更容易被滥用.

A switch is like any other control structure. There are places where it's the best/cleanest solution, and many more places where it's completely inappropriate. It's just abused way more than other control structures.

在 OO 设计中,在像您这样的情况下,通常认为最好使用从公共消息类继承的不同消息类型/类,然后使用重载方法自动"区分不同类型.

In OO design, it's generally considered preferable in a situation like yours to use different message types/classes that inherit from a common message class, then use overloaded methods to "automatically" differentiate between the different types.

在像您这样的情况下,您可以使用映射到您的操作代码的枚举,然后将一个属性附加到每个枚举值,这将允许您使用泛型或类型构建来构建不同的 Action 子类对象,以便重载方法将起作用.

In a case like yours, you could use an enumeration that maps to your action codes, then attach an attribute to each enumerated value that will let you use generics or type-building to build different Action sub-class objects so that the overloading method will work.

但这真的很痛苦.

评估在您的解决方案中是否存在可行的设计选项,例如枚举.如果没有,请使用开关.

Evaluate whether there's a design option such as the enumeration that is feasible in your solution. If not, just use the switch.

这篇关于switch 语句不好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆