Refactoring for the sake of compactness and reusability
2 min read
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>();
convertedType.Aggiudicatari =
MapArray<ICompanyDetail, SoggAggiudicatarioType>(awardCompanies,MapAwardCompanySoggAggiudicatarioType);
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>();
}