Wednesday, January 24, 2007

Postfix Inheritance : How would you do it?

Ok, I've got an object hierarchy I'm using to spit out a fairly lengthy XML document.  Every element in the system is basically unique except for one unifying feature - they can all have an optional element called Note, and if they do include Note, then Note has to have the same structure wherever it is used.  This element comes as the last child.  Got that?

Ok then.  What I want to do is create an abstract object XmlElement which basically has one method, ToXml, which will spit out the element as an XmlElement.  From there I create NoteElement which is a child of XmlElement that might have this optional Note inside of it.

Ok, so far so good.  I have all of my elements extend NoteElement, and then in the few cases where I want a Note I can simply add it, without having to rewrite it 100 times for 100 elements.

But!  When it comes to actually emitting the object as XML, how do I do it?  Ideally I want to say something up in NoteElement that says "Hey, don't forget about me...do whatever you want to do, but before you return, append me if I exist.  By doing it just once I don't have to individually write it 100 times.  99% of my objects will not have this information (although I have to write the support for it in there for spec compatibility, blah blah blah).

I'm trying to envision how to go about doing this.  I suppose one way is to have the ToXml method stop at NoteElement, and then have the others all implement a ToPartialXml or something like that.  Then NoteElement's ToXml method would simply call the appropriate ToPartialXml (which, for NoteElement, would be abstract so that the children have to supply a meaningful body), and then after that, tack on the Note if it exists.  Hmmm, that might work.

Blogging aloud because it's too late in the day for me to actually start up the code but I wanted to get the idea down.  Maybe somebody reading knows if I'm about to go down a dark and twisty path.

 

Technorati tags: , ,

No comments: