类设计:创建一个对象只是为了从子类创建对象是不好的形式吗?
我目前有一个消息系统,它写入两个表:sent
和 received
,它们基本上具有相同的架构。
我编写了一个名为 Message
的类,它在实例化两个子类之前填充用户输入的数据,这两个子类使用 Message
中的通用方法来设置其余属性并将每个属性写入数据库。唯一显着的区别是在子类中表示的一个字段及其相应的变量。所有其他属性都是 Message
的一部分。
问题是,Message
除了为创建的对象提供通用方法和属性并促进对其后代的数据库类的访问之外没有其他目的。
这被认为是不好的做法吗? Message
类是单一的还是我应该进一步推动它并为了一个字段而合并子类?更好的方法是将类完全分开,一个用于发送表,一个用于接收表?
I currently have a message system which writes to two tables, sent
and received
, which largely have the same schema.
I wrote a class called Message
which populates the user inputted data before instantiating the two child classes which use a common method in Message
to set the rest of the properties and writing each to the database. The only significant difference is one field which is represented in the child class with its corresponding variable. All of the other properties are part of Message
.
The thing is, Message
has no purpose other than to provide common methods and properties for the objects created and facilitate access to the database class it's a descendant of.
Is this considered bad practice? Is the Message
class monolithic or should I push it further and incorporate the child classes for the sake of one field? Would a better approach be to separate the classes entirely and have one for sent and one for received tables?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这不是一个糟糕的设计。您基本上创建了一个abstract类。此类类并不打算被实例化,而是包含其他几个类中常见的代码。
您遵循了一个原则:干 - 不要重复自己。
当然,如果差异真的很小,您可以通过将所有内容放在一个类中来使您的设计变得更容易。
It is not bad design. You basically created an abstract class. Such classes are not intended to be instantiated but contain code that is common in several other classes.
You followed a principle: DRY - Don't repeat yourself.
Of course, if the difference is really really small, you probably make your design easier by putting everything in one class.
那么,您有一个名为 Message 的类来实现通用功能,以及子类(即)
来实现“已发送消息”的特定任务吗?
这完全有道理。这仅取决于有多少功能是独立的。如果唯一的区别是 SentMessage 和 ReceivedMessage 被标记为“已发送”或“已接收” - 您最好在 Message 类中使用 getMessageType() 函数。但如果它更复杂,那么是的,你走在正确的道路上。
So you have class called Message that facilities common functions, and child classes (i.e.)
that facilitates specific tasks for a 'sent message'?
that makes perfect sense. It just depends how much functionality is seperate. If the only difference is that SentMessage and ReceivedMessage are marked 'sent' or 'received' - you'd be better off to have a getMessageType() function in your Message class instead. But if there is more complexity to it, then yes, you're on the right track.