开关语句是坏的? [英] Switch statements are bad?

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

问题描述

我最近得知,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.

但是考虑这个场景:I编写游戏服务器,从客户端接收消息,其中包含指示玩家行动的整数,例如移动,攻击,挑选项目等,将有超过30个不同的操作。当我编写代码来处理这些消息时,没有metter什么解决方案我想,它将不得不使用switch在某个地方。如果不是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设计中,通常认为在像yours这样的情况下使用不同的消息类型/类继承自一个通用的消息类,然后使用重载方法自动区分不同类型。

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.

在类似于yours的情况下,可以使用映射到您的操作代码的枚举,然后为每个枚举值附加属性,这将允许您使用泛型或类型构建来构建不同的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.

但是这是一个真正的痛苦。

But that's a real pain.

评估是否有一个设计选项,如枚举在你的解决方案是可行的。如果没有,只需使用开关。

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

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

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