继承与可测试性的组合 [英] inheritance vs. composition for testability

查看:102
本文介绍了继承与可测试性的组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在设计我的对象时,我发现从可测试性的角度来看,组合是更好的选择。原因是,如果需要的话,我可以在运行单元测试时模拟部分组合结构。如果我有一个继承层次结构,这是不可能的。

While designing my objects I find composition to be a better choice from the perspective of testability. The reason being, I can mock parts of the composition structure if I need to, while running unit tests. This is not possible if I have an inheritance hierarchy.

我想知道其他人是否也发现这是喜欢作曲的理由。还有什么其他可测试性陷阱,因为使用了继承?

I would like to know if others have also found this to be a reason to prefer composition. Also what other testability pitfalls did you get into because inheritance was used?

推荐答案

我相信你开始使用设计开发的越多模式,你会越来越多地发现组合比继承更受青睐。我实际上相信 Head First:Design Patterns 预订赞成组合而不是继承是主要的设计原则之一。

I believe that the more you start to develop using design patterns, you'll find more and more often where composition is going to be favored over inheritance. I actually believe in the Head First: Design Patterns book that "Favor Composition Over Inheritance" is one of the primary design principles.

你能够模拟部分构图进行测试的例子可能是最好的例子之一。

Your example of being able to mock up parts of the composition for testing is probably one of the best examples possible.

编辑:虽然设计模式的基本原则是支持组合而不是继承,但这并不意味着没有设计模式在需要的地方使用继承。另一个基本的例子是装饰器模式,你正在编写一个抽象的超类(虽然这是用于类型匹配而不是用于实现is-a关系)。

Edit: Although the basic principle in design patterns is to favor composition over inheritance, that doesn't mean that there aren't design patterns which utilize inheritance where it is needed. Another basic example is the decorator pattern, where you are coding towards an abstract superclass (although this is for type matching and not for implementing an "is-a" relationship).

这篇关于继承与可测试性的组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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