Anders G. Nordby

Lead Consultant at Itera

Monthly Archives: June 2013

Changing Code Comments to Something More Useful

Here is a little trick I showed my mentee the other day… Lets say that you have a Person object (maybe you get this this information from a database you’re integrating against), and you need to present various kinds of Person objects in different ways. This might be the code my mentee wrote:

private static void DisplayPerson(Person person)
{
    switch (person.Type)
    {
        // person is a normal employee
        case "H":
        case "R":
        case "F":
            {
                DoSomething(person);
                DoSomethingElse(person);
                break;
            }

        // person is a manager
        case "A":
        case "B":
            {
                DoSomethingSpecial(person);
                DoSomethingEvenMoreSpecial(person);
                break;
            }

        // treat person as normal employee
        default:
            {
                DoSomething(person);
                DoSomethingElse(person);
            }
    }
}

Notice the comments here! What if there are more person types showing up later? Or what if we’ll need the same kind of parsing person type elsewhere in our code? Instead, in cases like this, I suggest creating an enum based on the comments. (Please note that this is a contrived/simplified example, the real world solution was far more complex.) Below is my suggestion of how to improve the code:

private enum PersonType
{
    Employee,
    Manager
}

private static PersonType GetPersonType(Person person)
{
    switch (person.Type)
    {
        case "H":
        case "R":
        case "F":
            return PersonType.Employee;

        case "A":
        case "B":
            return PersonType.Manager;

        default:
            return PersonType.Employee;
    }
}

private static void DisplayPerson(Person person)
{
    switch (GetPersonType(person))
    {
        case PersonType.Employee:
            {
                DoSomething(person);
                DoSomethingElse(person);
                break;
            }

        case PersonType.Manager:
            {
                DoSomethingSpecial(person);
                DoSomethingEvenMoreSpecial(person);
                break;
            }
    }
}

Notice how the code is even easier to read than before. Also notice that by making the enum and the parsing code public (and possibly moving these elsewhere in the code), we can reuse the parsing in the rest of the project, should we ever need to do so. As a general rule, comments are dangerous, because they’re rarely updated as the code changes. Compiled parts of the code are more likely to be kept updated.

Advertisements