Showing posts with label patterns. Show all posts
Showing posts with label patterns. Show all posts

Friday, April 24, 2009

Simple reusable DTO factory methods

I have just found a little bug in my app that to me was an issue with code duplication. It was a DTO not getting properly hydrated when is was getting translated from a domain object in the service layer. My DTOs are just objects with auto properties, no business logic methods; just data carriers. I sometimes have the need for a basic DTO with just simple info (ie for Lists) and a more detailed DTO with the objects child collections (as DTOs collections) for more detailed views. The problem I had was when I added a field on to the domain object then had to modify my factory (and test) to ensure the new field was mapped. What I forgot to do was to also do it for my detailed DTO. I wtote the test and realised that I was doing the exact same work in 2 places, which was one of the reason behind the bug. As i prefer not to use anything other than a default constructor for DTOs i was in a bit of a quandry. Other than using JBogard's AutoMapper i was not sure how to tackle this.
My goodness, i may actually have to engage my brain!
Well the result was incredibly simple.
The detailed DTO (xyzDetailedDto) inherited from the normal DTO (xyzDto) so i just created a private generic factory method in the publicly exposed Extension method class

private static T Create(xyzDomianObject domainObj) where T : xyzDto, new()
{
return new T
{
Id = domainObj.Id,
Name = domainObj.Name,
Details = domainObj.Details,
OtherThing = domainObj.OtherThing
};
}

As xyzDetailedDto inherited from xyzDto I could reuse the creation method and get back the correct type.
This all seems very simple and silly now, but this has drastically cleaned up my translation layer :)

Friday, July 18, 2008

Design Patterns 101

How have i missed these!!!
JP Boo hoo hoo hoo ;) has some great intro's to Design Patterns on DNR TV. I am just watching the first of the series now so cant yet comment on the rest but so far so good. He presents it really well, but beware if you are not a ReSharper user it may be a bit of a tornado.

Check it out!
DotNetRocks TV Archives
John Paul's Design shows: 63, 65, 68, 71, 92

BTW Word on the street is JP's .Net courses are top-shelf-single-malt awesomeness. I have been recommended them from guys i respect in the community but have not had the chance to attend (get to the UK mate). If you get the chance to go to one at least investigate.

JP's Blog