I'm finding that the code that I write in my controllers is largely repetitive , and more importantly that the tests I write for my controllers are also very repetitive. The general pattern for a save method is as follows...
Take an entity, and a number of primitive parameters. Write the values from the primitive parameters onto the same named parameters on my entity. Validate the entity. Save the entity if it is valid.
I already have a model binder that will bind anything that inherits from IDataEntity (an interface that all our database persisted entities implement). This model binder finds the appropriate repository and looks up the entity with the passed id.
I have been considering adding an extension to this model binder that will also pull the values in from the value provider and write them over the existing values. This will save me some repetitive code in my actions assigning values to my entities. And will also allow me to just pass entities to my controller tests rather than a large number of values.
for example a method that currently looks like this:
public ActionResult SaveCompanyAddress(Address address,
string address1,
string address2,
string address3,
string city,
string county,
Country country,
string postcode)
{
address.Address1 = address1;
address.Address2 = address2;
address.Address3 = address3;
address.City = city;
address.County = county;
address.Country = country;
address.Postcode = postcode;
Validate(address);
if (ModelState.IsValid)
{
using (var tran = TransactionFactory.CreateTransaction())
{
addressRepository.Save(entity);
tran.Commit();
}
return this.RedirectToAction(x => x.List(address.Company));
}
else
{
return View("Edit", address);
}
}
Would be halved in length and have nearly all its arguments removed. This certainly sounds appealing as the amount of code we write is reduced, and a test to test validation can pass a mock validation provider and default address and not worry about setting all those parameters. but I am worried that there might be a little too much behind the scenes magic to make it a good idea.
Thoughts? Opnions? Ideas?