The question comes from the following issue: I have an abstract class Animal and two classes Dog and Cat that extend from it. I have the need to translate these classes into a JSON format, but I wish to do so in a way that is clean and proper. A few ideas came about:
1 - have abstract methods toJson() and fromJson() in the Animal class, that Cat and Dog must override, or simply create an interface JSONInterchangable or something. I have an issue with this since it seems to go against the single responsibility principle, because if i wished to have other methods of translation (like XML), i'd have to change the interface and further bloat the Cat and Dog class. Furthermore, the translating to json of all the properties in the Animal class would have to be repeated on all new overriden methods, and usually that much repetition seems bad
2 - use an existing library such as gson. I'm not a big fan of this solution as it would put a lot of assumption that i'd want a json format on my Animal classes, instead of changing to others in the future. Also, in the less animal-esque and real scenario i'm working on, I wouldn't want to make a direct translation as gson does, because of privacy and optimization concerns, so I'd prefer a custom way of translating to json that I could code.
3 - create a custom interface such as StorageTranslator<F, T>
and implement a StorageTranslator<Animal, JSONObject>
or StorageTranslator<Animal, XMLObject>
. This would seem ideal for be, but since the methods would receive an Animal, i couldn't really retrieve properties that are unique to the subclasses Cat and Dog (without using the instanceof operator a bunch, which seems like code smell)
I can't think of a solution that seems elegant. I guess 1 would be the better one, but it seems like it would place many responsibilities in those classes as more types would arrive. What would you guys suggest?
Aucun commentaire:
Enregistrer un commentaire