CodeSOD: Mastery Through Repetition
When I was a baby programmer, I subscribed to a computer magazine. In those olden times, these magazines would come with pages of program code, usually BASIC, so that you could type this program into your computer and run it. If you were careful about typos, you could accomplish quite a bit of "programming" without actually programming. What you were doing, in practice, was just typing.
One of Anthony's predecessors was quite the accomplished typist.
They needed to take the built-in .NET XmlDocument class and add a one method to it. Now, C# offers a few techniques for doing this. The "traditional" object-oriented approach is to use inheritance. Now, that's not without its downsides, so C# also has the concept of "extension methods". This is a little bit of syntactic sugar, which allows you to declare static method that takes a parameter of XmlDocument, but invoke it as if it were an actual instance method. Of course, depending on what you're doing, that might not give you all the functionality you need. And outside of those techniques, there are a number of the good-ol' Gang of Four design patterns, like the Visitor pattern which could solve this problem without loads of complexity. Or even just "a plain old static method" might fit.
But Anthony's predecessor didn't want to do any of those. They instead chose to use typing.
public XmlHelper() { doc = new XmlDocument(); } public XmlHelper(string xml) { doc = new XmlDocument(); this.doc.LoadXml(xml); } public XmlHelper(XmlDocument doc) { this.doc = doc; } public void Attach(XmlDocument doc) { this.doc = doc; } public void LoadXml(string xml) { this.doc.LoadXml(xml); } public void LoadFromFile(string filePath) { this.doc.Load(filePath); } public XmlNode SelectSingleNode(string xpath) { return this.doc.SelectSingleNode(xpath); } public XmlNodeList SelectNodes(string xpath) { return this.doc.SelectNodes(xpath); }.... // another dozen similar overloads public XmlNodeList GetFilteredNodeList() { return DoSomeFilteringOnMyNodeList(this.doc); }// another dozen of trivial overloads}
The XmlHelper class exposes all of the same methods as an XmlDocument, but adds a single GetFilteredNodeList. Because we didn't use inheritance, you can't slot an XmlHelper in the same place as an XmlDocument, but they both have the same interface (but don't actually implement a common Interface). In short, this is a lot of code with no real benefit.
But I'm sure the developer was a very good typist.
[Advertisement] BuildMaster allows you to create a self-service release management platform that allows different teams to manage their applications. Explore how!