拥有一个无处不在的基础对象是一种反模式吗?
我记得在某处看到过关于此问题的辩论,目前正在考虑删除我正在开发的系统中每个业务对象都继承自的基本对象。 它包含一些属性、一些数据库逻辑和一些构造函数逻辑。
这是一种反模式,还是尚无定论? 拥有一个可以继承的基础合约会更好吗?这需要在每个对象中完成一定量的样板编码?
编辑:我确实喜欢 dsimcha 并且觉得它很好地反映了这个问题,我仍然很高兴听到任何进一步的答案
I remember seeing a debate about this somewhere, and am currently considering removing a base object that every business object, in a system I'm working on, inherits from. It contains a few properties, some database logic, and some constructor logic.
Is this an anti pattern, or is the jury still out? Would it be better to have a base contract to inherit from, which would require a certain amount of boilerplate coding to be done in each object?
EDIT: I do like dsimcha and feel it reflects very well on the issue, I am still happy to hear any further answers
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
标准的经验法则是仅使用继承来通过多态性为类的用户提供灵活性,如果您想重用其他类的代码,则使用组合。 但是,只要您不违反 里氏替换原则,情况可能还不错。 编写大量的样板文件本质上也是一件坏事,因为它掩盖了代码中真正发生操作的部分,并且是反 DRY 的。 但是,如果您违反了里氏替换原则,那么这绝对是一个坏主意。
The standard rule of thumb is to use inheritance only to provide flexibility for users of a class through polymorphism, and use composition if you want to reuse code from other classes. However, as long as you're not violating the Liskov Substitution Principle it's probably not too bad. Writing tons of boilerplate is inherently a bad thing, too, since it obscures the parts of your code where the real action is happening and is anti-DRY. If you are violating the Liskov Substitution Principle, though, then absolutely this is a bad idea.
一个潜在的问题是,如果您使用多重继承:您的子类然后继承“Eve”类的两个实例...这就是为什么 C++ 支持所谓的虚拟继承。
这是一个经常使用的习惯用法:例如,在 .Net 中,一切都源自 System.Object ……和/或,所有 COM 对象都实现 IQueryInterface 接口。
A potential problem is if you use multiple inheritance: your subclass then inherits two instances of the 'Eve' classes ... which is why C++ supports so-called virtual inheritance.
It's a frequently-used idiom: for example in .Net everything derives from
System.Object
... and/or, all COM objects implement the IQueryInterface interface.没有什么是真空中的反模式。 你的“夏娃课”给你带来了问题吗? 您希望删除它会带来什么好处? 询问它是否在一些标准的反模式列表上只有在有助于识别时才有帮助实际问题。
Nothing is an anti-pattern in a vacuum. Is your 'Eve class' causing you problems? What benefits do you expect to realize from removing it? Asking whether it's on some standard list of anti-patterns only helps if it aids in identifying actual issues.