我们应该总是喜欢枚举的多态吗? [英] Should we always favor polymorphism over enums?

查看:138
本文介绍了我们应该总是喜欢枚举的多态吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

观看后:清洁代码会话 - 继承,多态,&测试

我检查了我的代码,注意到一些switch语句可以重构为多态,但是我也注意到我只使用带有枚举的switch语句。这是否意味着枚举在OO设计中是邪恶的,应该用多态来消除?

I checked my code and noticed a few switch statements can be refactored into polymorphism, but I also noticed I only used switch statements with enums. Does this mean enums are "evil" in OO-design and should be eliminated with polymorphism?

推荐答案

这不是枚举是邪恶的,它是switch语句。在 C ++常见问题书籍中进行了长时间的讨论,但其主旨是:除了对于有限的区域---例如从设备上的注册表中输入的数据的解释---大的开关梳子表明您正在使用数据来区分子类型。为此,您应该只使用子类型,获得编译器的帮助来保持正确,并且也意味着当您(不可避免地)更改一组案例时,编译器将自动添加新的案例。

It's not that enums are evil, it's switch statements. There's a long discussion of this in the C++ FAQ Book, but the gist is this: except for limited areas --- for example the interpretation of data coming in from a register on a device --- a big switch comb suggests that you're using data to distinguish among subtypes. In place of that, you ought to just use subtypes, gaining the compiler's help in keeping it correct, and also meaning the compiler will automatically add new cases when you (inevitably) change the set of cases.

这篇关于我们应该总是喜欢枚举的多态吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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