Comment Smell

|

Here's some code from the rather interesting blog "Extreme Programming - Simulating an XP project":

public string SaveToXml()
{
    XmlDocument document = new XmlDocument();

    //Create a root node called task
    XmlElement rootNode = document.CreateElement("Task");
    document.AppendChild(rootNode);

    //If the name exists, store this information
    if (this.Attributes.Contains("Name"))
    {
        //Append the name information as an attribute
        XmlAttribute nameAttribute = document.CreateAttribute("Name");
        nameAttribute.InnerText = this.Attributes["Name"].ToString();
        rootNode.Attributes.Append(nameAttribute);
    }

    //If the creation date exists, store this information
    if (this.Attributes.Contains("CreationDate"))
    {
        //Append the creation date information as an attribute
        XmlAttribute creationDateAttribute = document.CreateAttribute("CreationDate");
        creationDateAttribute.InnerText = this.Attributes["CreationDate"].ToString();
        rootNode.Attributes.Append(creationDateAttribute);
    }

    //If the due date exists, store this information
    if (this.Attributes.Contains("DueDate"))
    {
        //Append the due date information as an attribute
        XmlAttribute dueDateAttribute = document.CreateAttribute("DueDate");
        dueDateAttribute.InnerText = this.Attributes["DueDate"].ToString();
        rootNode.Attributes.Append(dueDateAttribute);
    }
}

It's a rather typical example for a "Comment smell":

  • The comments are not needed because the code communicates very clearly what is done (even to someone like me who's not an XML-Guru at all)
  • If the comments are not needed, we should get rid of them because they pollute the code plus they will get out of sync with the code in the long term (Can you say "Cut/Copy/Paste"? :-)

Plus, the comments are hints on potential refactorings like extract method.

About this Entry

This page contains a single entry by HMK published on September 26, 2006 7:33 PM.

Excellent Blog on Testing was the previous entry in this blog.

Niklaus Wirth books is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.