开发者

Class design: is creating an object just for creation of objects from child classes bad form?

开发者 https://www.devze.com 2023-01-02 13:56 出处:网络
I currently have a message system which writes to two tables, sent and received, which largely have the same schema.

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 o开发者_如何学Gof one field? Would a better approach be to separate the classes entirely and have one for sent and one for received tables?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消