问题描述
我使用接口/抽象基类为我的大多数类型,并不经常从具体类继承,但我最近遇到了需要继承或组合的情况。我已经意识到广告程序到接口,而不是实现,但最近决定深入。
I use interfaces/abstract base classes for most of my types and don't often inherit from concrete classes but I've recently run into a situation where either inheritance or composition is desired. I've been aware of the adage "program to an interface, not an implementation" but recently decided to dig deeper.
我看到过 ,我看到计数器,但我很好奇其他大型代码库的维护者在现实生活中实际做了什么。恐惧过度吗?你从具体类继承,还是继承怀疑论正确?
I've seen arguments against inheritance, and I've seen counter arguments but I'm curious as to what other maintainers of large code bases actually do in real life. Is the fear overblown? Do you inherit from concrete classes, or are the inheritance skeptics correct? I'm particularly interested in hearing from those people that work in C++.
推荐答案
不是C ++的家伙(有专业经验的大企业系统在c#,java和ruby),但这里是我的2美分
Not a C++ guy (have professional experience with big enterprise systems in c#, java, and ruby), but here is my 2 cents anyways
这不是一个黑白的东西。
This isn't a black and white thing.
继承的问题是它引入了紧耦合。更糟的是,耦合通常在封装状态。超类中的更改可以在继承层次结构中产生波纹效应,从而创建微妙和难以预测的错误。
The problem with inheritance is that it introduces tight coupling. Worse, that coupling is usually around encapsulated state. Changes in super classes can have rippling effects down inheritance hierarchies, creating subtle and hard to predict bugs.
接口隔离完全回避了这些问题,因为它不会破坏封装同样的方式。
Interface segregation totally sidesteps those issues, because it doesn't break encapsulation the same way.
继承的好处是,有时你有一个对象模型,真的是一样的东西,只是一个非常小的变化或添加。只要该变化非常清楚,范围不会广泛,并且不是附加约束(请参见问题),代码重用将胜过紧耦合。
The good thing about inheritance is that sometimes you have an object model that really is the same thing, just with a very small change or addition. As long as that change is very clear, not wide reaching in scope, and isn't an additional constraint (see the circle-ellipse problem), the code reuse will trump the tight coupling.
我坚持组合而不是继承法。
I stick to composition over inheritance as a rule of thumb, not a law.
这篇关于具体类的继承是邪恶的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!