Starbucks-fueled Developer

Thursday, February 17, 2005

DTOs: What's the Point?

Scott, after I sent him an e-mail, read my post about serializing ADAPTERS to XML, sent me the following reply:

"I don't know enough about XML serialization to be able to speak to theproblem in any significant depth.

Am I understanding that you're serializing the adapter? If so, that's areally uncommon thing to do. Adapters often sit at component boundaries,but aren't often passed back and forth between them... kinda contradicts thenotion of an adapter.

Maybe what you need is the Data Transfer Object(

Rather than serialize raw objects, put the raw objects' data into a simpler structure that can be more easily serialized. DTO's are intended for moving data between boundaries.

Beyond that, it's hard for me to say without really having hands-on experience with the serializer."

I think he's right; I missed the point of the ADAPTER pattern, to a degree. I think my intention was correct, in trying to decouple the application from a particular service implementation. I think I got that part right. The ADAPTER is allowing an object from an external library that provides the desired functionality by providing the "client" an interface to it, that it is expeciting, so that it is usuable (boy, that seems awfully wordy...).

But here's where I get lost in this whole OOP/TDD thing: why should I create that Data Transfer Object when the runtime will persist the object to the desired format for me? For instance, take the example given in the link Scott referenced in his reply, Fowler's DTO. The AlbumDTO class has a ToXmlElement() method; this is perfect for Java - at least to my understanding - because Java doesn't have a way to easily persist an object to and from XML without actually writing out the representation using some-sort-of XML StreamWriter. The programmer has to write that code manually saying "write an element named 'album' and add a 'title' attribute and a child element named 'artist' with the artist's name as it's text" (that would result in <album name="asdf"><artist>Foo</artist></album> for clarification). Who in their right mind would go through all that?! (aside: I might entertain a discussion on that issue some other time)

In the world of .NET, the XmlSerializer will persist the entire object graph to XML, unless you instruct it to do otherwise. Why would I write a DTO if the runtime does this for me? In fact, when you write a Web Service and return an object, the runtime invokes the XmlSerializer on your object to return your object to the client anyway! I had the same beef with DTOs when they appeared in Newkirk's .NET TDD book.

I realize I could be over-generalizing things here, but I still feel my point is valid, arguable to say the least: do DTOs have a purpose in .NET when the runtime provides these services for us?


Post a Comment

Links to this post:

Create a Link

<< Home