Tuesday, September 6, 2011

A Clear Example of The Dont Repeat Yourself Principle

The DRY principle is something all developers most often than not want to achieve. Don't Repeat Yourself. Meaning you shouldn't repeat code.

In a recent project, we created a simple, custom XML feed returning a couple of nodes with image meta data.

To build custom XML feeds, XmlDocument is very common to use in the .NET world. Adding nodes can be done using XmlNode.

The code we had looked like this:

// ...
XmlNode imgNode = doc.CreateElement("LatestImage");

XmlNode imgCountry = doc.CreateElement("Country");
imgCountry.InnerText = LocationHandler.GetLocationAlias(img.GeoTag.Country.LocationID, "sv").Country;

XmlNode imgLocation = doc.CreateElement("Location");
imgLocation.InnerText = LocationHandler.GetLocationAlias(img.GeoTag.LocationID, "sv").Name;

XmlNode imgDate = doc.CreateElement("Date");
imgDate.InnerText = img.UploadDate.ToString();

// ....


// ...

It does the job, but not good enough. A lot of XmlNodes created manually. By adding a simple method and utilizing it instead, it will be much easier.

The clever method:

private XmlNode AddNode(string nodeName, string nodeValue, XmlDocument doc, XmlNode parentNode)
XmlNode node = doc.CreateElement(nodeName);
node.InnerText = nodeValue;


return node;

And this is how we use the AddNode method to add new nodes:

AddNode("Location", LocationHandler.GetLocationAlias(img.GeoTag.LocationID, "sv").Name, doc, imgNode);

Much, much better. Utilizing the AddNode method, we reduced the actual code with almost 50 % (from 21 rows to 11).

A clear example of implementing the DRY principle.

Note: It's also clever to use XDocument instead of XmlDocument to create XML files, but that's for another time!