Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

problem with inheritance / polymorphism

 
Alison Brown
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've got an incoming XML message. One of the fields inside it tells me what sort of message has to be generated from it, there are currently 5 different ones I've got to deal with, so I've got 1 base class (with a build method) & 5 subclasses for this. I can't think of a nice way to handle the subclass constructors though. I've thought of 2 variations which are basically the same, but both are pretty bad. There has to be a clever way of doing it but I don't know what it is.

1. declare msg of class baseclass
if xml says its baseclass 1 then
msg = new baseclass1 ()
else if msg says its baseclass2 then
msg = new baseclass2 ()
else if ....
else
raise error as unrecognised message, return
end if;
msg.build ();

2. have a hash table of message codes to integers returning 0 if not found
switch (on the int returned from the hash look up)
case 1 : msg = new baseclass1 ()
case 2 : msg = new basseclass2 ()
...
default : raise error as unrecognised message, return

end switch;
msg.build ();

With both of these, this code has to change whenever a new subclass is introduced, which is what I want to avoid.
Any ideas?
:confused
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How about the following scenario -- suppose you have N messages represented by N derived classes. Suppose you stick the following associations in a properties file (or a preferences object)

Given a 'MSG_i' string, it is easy to find the associated fully qualified classname (if it exists). Given this name, the following snippet instantiates the corresponding object:

et voila. If a new message is introduced, simply add a new derived class for it in your jar and add a line to the properties (of preferences) file.
kind regards
 
Alison Brown
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks very much, that's exactly what I needed to know.
 
Michael Morris
Ranch Hand
Posts: 3451
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Alison,
Looks like a job for the good old Factory pattern to me. Something like this:

XMLMessage would be either an abstract base class or maybe just an interface. So you would just call

Hope this helps,
Michael Morris
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic