So I have a very basic problem with no doubt a very basic solution which at the present time is eluding me.

For some reason on this project 90% of the objects I work with are already in existence (in the database as well as conceptually in space-time !). Therefore most creation code for my entities is just for the purposes of reconstituting an object from a DTO. This is where I am having the problem. In a piece of functionality I haven’t even fully implemented yet I have the following:

public class MyEntityDTO
{
	public int OneField { get; set; }
	public string AnotherField { get; set; }
}
 
public class MyEntity
{
	private readonly int oneField;
	private readonly string anotherField;
	public MyEntity(MyEntityDTO dto)
	{
		oneField = dto.OneField;
		anotherField = dto.AnotherField;
	}
 
	public MyEntityDTO CreateDTO()
	{
		return new MyEntityDTO(...;
	}
 
	... insert domain logic here...
}

And a test akin to:

[TestFixture]
public class When_MyEntity_Is_Reconstituted_From_DTO
{
 
	private MyEntityDTO DTO {get; set;}
	public override When()
	{
		DTO = Builder.CreateWithAllFieldsFilledIn();
		Result = new MyEntity(DTO);
	}
	[Test]
	public void AnotherField_Is_Copied_In()
	{
		Result.AnotherField.ShouldEqual(DTO.AnotherField);
	}
}

… and a similar test to test persistence to a DTO.

OK for starters, but I know that somewhere down the line, ‘MyEntity’ is going to get quite a few more properties and value objects. So when I add a new property I have to do the following:

  • Write a new test to test that the DTO property is copied to the MyEntity instance (thanking goodness for BDD style testing which makes this very simple)
  • Write a new test to test that the MyEntity property is copied to the DTO
  • Implement the property in the DTO
  • Implement the property in MyEntity

Already this is getting my lazy-senses tingling. It’s only one property! What happens if I refactor three properties into a value object or add a dozen more. I can’t guarentee that future me is going to want to go through all those steps. Problem is I can’t see any way to simplify this in just code alone.

In an ideal world, I would use NHibernate, do away with the DTO and let my mapping do the work. However, this would contravene the NIH rule of the current project I am working on. My data access layer is all hand-coded SQL so I try and keep it’s work to the absolute bare minimum (still seems to be where 99% of the bugs lie but that’s another story…).

Another idea would be to use automapper (which I have been meaning to try for a while now) but I am stuck in 2.0 so no go there I presume.

I guess at the end of the day most coding problems are social – maybe I should be using NHibernate here and screw NIH syndrome!