I’m reading a HTTP POST and the body of the HTTP request can be either JSON or XML. Now I’ve delegated the reading to a special utility class.
interface HttpUtils { BodyWrapper parseBody( HttpServletRequest req ); } interface BodyWrapper { boolean isXML(); // 1 boolean isJSON(); // 2 String body(); // 3 }
- I hate the fact that BodyWrapper has methods (1 & 2) to identify its type. Perhaps I should use inheritance. If I do that, I will need to do an instanceof to find out what is being returned by HttpUtils.parseBody(..)
- Ideally I would also want the body() method to return either a JSONObject or an DOM node. How would I do that?
Don’t ask your objects for information, and then make decisions on what they tell you. Make your objects do the work for you. That is, don’t do this:
It’s a maintenance headache. Do something like this instead (the BodyWrapper implementations would created using an abstract factory method or similar)
and then:
That way, something creates the appropriate
BodyWrapperimplementation, and then instead of asking it what type it is, you just use it. Note that the BodyWrapper isn’t returning different types of internal structures, because it (perhaps an abstract base class) is doing the work for you.