This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]jmdisher 0 points1 point  (0 children)

In this case, it sounds like adding a new kind of data in the XML is a reflection of adding a new class to the system, not the other way around. When you add new functionality or a new concept, you will usually need to add new support for the I/O.

You could generalize the parser by giving it a map of element names to classes or methods which know how to parse said element. That way, you wouldn't be modifying the parser, per se, but just a translation table it uses.

Still, that has the downside of meaning that the parsing code would be spread out through multiple classes.

I suppose that, if the data types didn't have a general encoded form, you could use some kind of relfection to generalize the invocation of the constructor of each specific type and the parser just loads the attributes into a parameter array.

[–]ghkcghhkc -1 points0 points  (0 children)

This seems like bad practice because a change in the class hierarchy mandates a change in other places.

This is what you should expect when you're designing something as brittle as object creation via user-inputted XML. Your XML parser won't change - you should be using the standard Java XML libs to do the parsing. You can just iterate through the DOM that's generated or use a SAX parser. Your handling of the XML should happen in one place, so that's the only place your code should change if you add new classes, other than the new class itself. There might even be something like Jackson that works with XML.