Categories
Archives
- August 2008
- July 2008
- June 2008
- May 2008
- April 2008
- March 2008
- February 2008
- January 2008
- December 2007
- November 2007
- October 2007
- September 2007
- August 2007
- July 2007
- June 2007
- April 2007
- March 2007
- February 2007
- January 2007
- November 2006
- October 2006
- September 2006
- August 2006
- July 2006
- June 2006
- May 2006
DoubleChecking your PHP | Home | RESTful Hullabaloo
Filed under Quick Tips on August 15, 2008 by Joel PotischmanEmpty Subclasses Are Good
I write lots of server-side software with XML APIs. I'm constantly taking an XML document as input, maybe transforming it to another format, sending that XML doc somewhere for processing, then returning the resulting XML back to the client. It's all nice and flexible and loosely coupled, but if all my parameters are of type XmlDocument my code is hard to read, and I may accidentally confuse parameters and still compile just fine. By subclassing XmlDocument and adding no new code, I can get compile-time checks against parameter confusion, better readability, and all the XmlDocument functionality I know and love still works unchanged.
Let's say my service uses adapters that implement the following interface:
I have some app code to execute against an IMyProcessAdapter-implementing class:
No problem. Everything compiles and runs just fine. However, the following code also compiles just fine, even though I've gotten all my XmlDocument parameters confused:
But what if I subclassed XmlDocument for each parameter? I don't actually add any functionality to these new classes, though of course I could some day. I'm just asking the compiler to ensure that every time I pass an XmlDocument parameter it's really the one I mean to use. Here's my new interface declaration with these new subclasses:
My code is now easier to read, as its intent is much clearer, and any accidental substitution of a RawInput for a ProcessSubmission will result in a compilation error, not a bug late in testing or production:
And of course, since all these parameters inherit from XmlDocument, I can call myProcessResults.SelectSingleNode("//whatever"), myProcessSubmission.LoadXml("<hi mom/>"), etc. If there's a downside to this approach, please let me know in the comments, because I can't find it.
Trackback Pings (TrackBack URL for this entry)
http://www.arc90.com/cgi-bin/mt4/mt-tb.cgi/182.
DoubleChecking your PHP | Main | RESTful Hullabaloo
