I'm curious to hear if anyone has any suggestions or alternative patterns for building a custom object with data from another object.
We're exploring three approaches currently.
1) Static Build Method
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
public static MyObject Build(DataRow data)
{
MyObject newObject = new MyObject();
newObject.Id = Convert.ToInt32(data["ID"]);
newObject.Name = Convert.ToString(data["NAME"]);
return newOjbect;
}
}
2) Builder Class
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public class MyObjectBuilder
{
public static MyObject Build(DataRow data)
{
MyObject newObject = new MyObject();
newObject.Id = Convert.ToInt32(data["ID"]);
newObject.Name = Convert.ToString(data["NAME"]);
return newOjbect;
}
}
3) Extension Method
public class MyObject
{
public int Id { get; set; }
public string Name { get; set; }
}
public static class MyObjectExtensions
{
public static void Build(this MyObject obj, DataRow data)
{
obj.Id = Convert.ToInt32(data["ID"]);
obj.Name = Convert.ToString(data["NAME"]);
}
}
One main consideration is that which ever approach we go with we need to add a using
reference of System.Data
to the class. At this point we're hesitant to add this dependency directly to our MyObject
class.
Can anyone offer advantages or disadvantages to any of these approaches or perhaps offer alternatives that would better enable extensibility and testability?
Disadvantage of the first approach is that you mix up the object definition with the builder logic. Considering the overall architecture you opt for, you might prefer to keep your model objects as being POCOs therefore not having the copy logic defined in it.
I wouldn't use the extension method either, as they are in my opinion, more relevant to extend features from the framework (typically the string or IEnumerable classes) when you need a specific feature through all your project.
So the second solution is interesting since it allows you to separate the object definition from the building logic. However, you might consider the number of objects you want this to be applied. If you have many of them, it could become a mess to maintain.