是否可以使用重复继承来使类更小?
我有一个很长的类,我无法拆分它,因为我需要一个数据库表(Google AppEngine + Objectify)中的所有字段。我已经尽可能使用嵌入式类。该类主要由 getter 和 setter 以及它们背后的逻辑组成。
为了获得功能块,我决定使用重复继承。现在看起来像这样:
MyStoredModel extends
AbstractSettingsModel extends
AbstractHierarchyModel
(处理父/子对象)extends
AbstractInformationModel
(包含标题,描述,...)extends
- .....
AbstractModel
更容易看到每个类都在做什么,我还想说它更容易测试。缺点是“继承链”。
这是否被视为不良行为?有哪些更好的方法可以缩小班级规模?
I had a long class which I couldn't split up because I need all the fields in one database table (Google AppEngine + Objectify). I'm already using embedded classes wherever possible. The class consists mostly of getters and setters plus the logic behind them.
In order to get functional chunks I decided to use repeated inheritance. Now it looks like this:
MyStoredModel extends
AbstractSettingsModel extends
AbstractHierarchyModel
(dealing with parent/child objects)extends
AbstractInformationModel
(holds title, description, ...)extends
- .....
AbstractModel
It's easier to see what every class is doing and I'd also say it's easier to test. The downside is the "inheritance chain".
Is that considered bad behavior? What are be better ways to make the class smaller?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会考虑使用组合来实现这些。因此该模型由设置、层次结构、信息对象组成。
这确实意味着您必须在顶级对象上包含所有 setter/getter,然后将其委托给每个组件类中各自的 setter/getter,但至少您可以将它们的所有处理隔离到单独的类中没有继承层次结构的复杂性。这也意味着这些组件类现在可以自由地继承它们喜欢的任何内容。
I'd think about using composition for these. So the model consists of Settings, Hierarchy, Information objects.
It does mean you have to include all the setter/getters on the top-level object, which would then delegate to the respective setters/getters in each of those component classes, but at least you can isolate all the handling of them into separate classes without the complexity of an inheritance hierarchy. And it also means those component classes are now free to inherit from anything they like.
只要继承从逻辑角度来看是有意义的,我就很确定它应该是这样的。
但组合也是一个好主意。
As long as the inheritance makes sense in a logic perspective, I'm pretty sure that's the ways it's supposed to be.
But composition can also be a good idea.