Preface
In an application that is separated by layers or distributed by services it is common to have classes that are very closely related data-wise, but which we wish to have loosely coupled. My usual solution (in c#) is to have them implement a common interface. (There are other patterns, but this is what I default to)
I might (for example) have a backend data entity Foo
public class Foo:IFoo
{
public int DatabaseKey {get; set;}
public string NaturalKey {get; set;}
public string SomeProperty {get; set;}
}
a data contract class FooDto
[DataContract]
public class FooDto:IFoo
{
[DataMember]
public string NaturalKey {get; set;}
[DataMember]
public string SomeProperty {get; set;}
}
and an MVC model class FooModel
public class FooModel:IFoo
{
public string NaturalKey {get; set;}
public string SomeProperty {get; set;}
public string CssClass {get; set;}
}
all implementing a common interface IFoo
public interface IFoo
{
string NaturalKey {get;}
string SomeProperty {get;}
}
My Question
When mapping those incarnations of Foo onto each other I might use an object mapper (ie automapper), but for smaller projects or when policy prevents third party software I add a constructor which takes the interface as a parameter, ie
public Foo(IFoo template):base()
{
NaturalKey = template.NaturalKey;
SomeProperty = template.SomeProperty;
//additional code
}
etc
How can I avoid unnecessarily repeating the assignments from template to properties across the different classes? Assume that the general pattern is given as is the decision not to use an object mapper. Note that the assignments might differ in some cases (inferring explicit defaults for null values etc)