Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Extending classes in which member variables also need to be extended

 
Nathan England
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Greetings all! I have a puzzling issue on how to properly design some relatively simple objects. Lets say I start out with a simple data object, whose members are also other data objects.

(In the examples below, the IOrderDetail and IOrder are interfaces that define getter setter signatures)






I want to create a couple of classes that tack on some additional functionality, for example, to add some methods to Order and OrderDetail that generate XML to represent those objects (Order and OrderDetail). I use XML as an example here, but what I really am trying to do is extend an Order, while at the same time extend the OrderDetail to implement the same interface.

so I came up with an interface




The trouble I'm having, is when am coding the Order object, which now needs a new member variable of an extended type OrderDetail. My problem is, I'm just not sure if this is proper design or not.



Is this the correct approach? If I have a bunch of classes that are member variables of another class, I would have to go and edit all of those classes and add new member variables that are extensions of others. It seems difficult to maintain this kind of design, and the less extendable it becomes.
 
Rob Spoor
Sheriff
Pie
Posts: 20550
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I don't think this is a good approach; if you need to switch from a non-XML instance to an XML instance you're going to have some difficulties.

Instead, I'd create a second little "framework", based on one (generic) interface: XMLOutputter<E>. You then create one implementing class for all your classes:
So instead of calling generateXML() on an IXMLOutable, you create a new XMLOutputter for each object you want to convert to XML. Perhaps you use a factory class for creating these XMLOutputters for the objects. Perhaps you can even use generics: type XYZ will get an XMLOutputter class XYZXMLOutputter.
 
Nathan England
Greenhorn
Posts: 20
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Rob!

And yes, this is exactly the problem I seem to be running into. I have to switch between the xml and non-xml and it's getting quite confusing. The framework you present makes a lot of sense, I will give it a try.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic