I was going back through an application I am currently working on for a client and trying to come up with a way to bridge a gap between that application and a new web site they want, which has two separate application architectures and ORM solutions. I realized how some of my errors have come to light, and how the SRP principle could have came in handy. Let me explain.
When using an ORM solution like LINQ to SQL or ADO.NET Entity Framework, each of these ORM's generates its own class and so you can't simply reuse these objects if each project has it's own class definition generated. One of my coding blunders has come to light in relation to SRP. Imagine having a plain old CLR object (POCO) that receives data from an ORM generated class as such:
//Class to receive data from a Customer LINQ to SQL class
public class CustomerData
{
public int Key { get; set; }
public string Name { get; set; }
.
.
}
One of the convenient ways to load this object that I would do would be to add a method that does this, within CustomerData:
public static CustomerData FromCustomer(Customer linqToSqlObj)
{
return new CustomerData
{
Key = linqToSqlObj.Key,
Name = linqToSqlObj.Name
};
}
And so this static method helped quickly create an instance. The problem with this approach is that now I have a class customized for my LINQ to SQL project. If I want to say use it for a shared project, a project that's shared across multiple projects which may have multiple ORM's, this shared project can't have access to the data access layer (well it shouldn't if it's a shared project) and so the challenge then becomes how can you create this class?
There are a couple of approaches. One I've used is to use extension methods. This allows an attachment of a method to do the conversion in a project that can access both objects. This class could look like:
public static class CustomerDataExtensions
{
public static CustomerData FromCustomerFromCustomer(this Customer linqToSqlObj)
{
return new CustomerData
{
Key = linqToSqlObj.Key,
Name = linqToSqlObj.Name
};
}
}
This extension method appends a conversion method onto the LINQ object. In this way, the responsibilities are separated, even though they may appear not to be.
Image may be NSFW.Clik here to view.
