Juri Strumpflohner
Juri Strumpflohner Juri is a full stack developer and tech lead with a special passion for the web and frontend development. He creates online videos for Egghead.io, writes articles on his blog and for tech magazines, speaks at conferences and holds training workshops. Juri is also a recognized Google Developer Expert in Web Technologies

Refactoring for the sake of compactness and reusability

2 min read

Currently I'm doing a rather monotonic work, let's call it like this. We basically need to serialize our data to an XML file that has to match a given XSD which has been given to us by our customer. The problem, the XSD has not nearly the same structure of our own domain model which implies a lot of property 1-1 mapping between the C# objects generated from the XSD file and our domain model. Automatism?? Not really applicable. I tried already to figure out to which degree libs like AutoMapper could be useful but concluded that it wouldn't really bring much in the end.

A nice thing when coding such object mappings is that there emerge patterns which can then be refactored nicely, also because these mapping stores involve an overall structural/architectural design initially but then they are nearly a pure typing exercise (which often isn't that bad too). Take the example below:

List<SoggAggiudicatarioType> soggAggiudicatarioTypes = new List<SoggAggiudicatarioType>();
if (awardCompanies != null)
{
foreach (ICompanyDetail companyDetail in awardCompanies)
{
soggAggiudicatarioTypes.Add(MapAwardCompanySoggAggiudicatarioType(companyDetail));
}
}
convertedType.Aggiudicatari = soggAggiudicatarioTypes.ToArray<SoggAggiudicatarioType>();

This was one re-occurring pattern. A list of objects from our domain model had to be mapped accordingly to an array of a generated XSD type. Lot's of mostly similar constructs emerged so I refactored the whole stuff above to the following:

convertedType.Aggiudicatari = 
MapArray<ICompanyDetail, SoggAggiudicatarioType>(awardCompanies,MapAwardCompanySoggAggiudicatarioType);

Transforms in a nice one-liner :) and saves you from cramps in your fingers ;) . But the code hasn't disappeared, it has just been refactored to the given, generic method:

protected TConvertTo[] MapArray<TConvertFrom, TConvertTo>(List<TConvertFrom> sourceData, Func<TConvertFrom, TConvertTo> convertFunction)
{
List<TConvertTo> convertedResult = new List<TConvertTo>();
if (sourceData != null)
{
foreach (TConvertFrom sourceItem in sourceData)
{
TConvertTo converted = convertFunction.Invoke(sourceItem);
convertedResult.Add(converted);
}
}

return convertedResult.ToArray<TConvertTo>();
}

Questions? Thoughts? Hit me up on Twitter
comments powered by Disqus