类设计:创建一个对象只是为了从子类创建对象是不好的形式吗?

发布于 2024-09-04 08:26:02 字数 437 浏览 8 评论 0原文

我目前有一个消息系统,它写入两个表:sentreceived,它们基​​本上具有相同的架构。

我编写了一个名为 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 Messageto 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

悲念泪 2024-09-11 08:26:02

这不是一个糟糕的设计。您基本上创建了一个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.

心的憧憬 2024-09-11 08:26:02

那么,您有一个名为 Message 的类来实现通用功能,以及子类(即)

class SentMessage extends Message {

来实现“已发送消息”的特定任务吗?

这完全有道理。这仅取决于有多少功能是独立的。如果唯一的区别是 SentMessage 和 ReceivedMessage 被标记为“已发送”或“已接收” - 您最好在 Message 类中使用 getMessageType() 函数。但如果它更复杂,那么是的,你走在正确的道路上。

So you have class called Message that facilities common functions, and child classes (i.e.)

class SentMessage extends Message {

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文