Pages

Monday, May 30, 2011

Code Verification During Development

This post is not for people who use TDD or use unit test.

Here, I am going to talk about a simple idea that lots of you may know about it but aren't using it. And that is 'Immediate Window'.

Immediate window is not just about running simple expressions like '2+2', the subtle point is that you can refer to your objects in your codes.

Imagine you are going to develop a simple method to get all the possible substrings of a text:

public static List<string> GetAllSubTexts(string name)
{
    var result = new List<string>();
    var characters = name.ToCharArray();
    for (int from = 0 ; from < characters.Length - 1 ; from++) {
        for (int to = from + 1 ; to <= characters.Length ; to++) {
            var currentTarget = name.Substring(from , to - from);
            result.Add(currentTarget);
        }
    }

    return result;
}
The above codes seems to work properly. So you may follow your coding without testing and forget this method. One reason developers usually do not do the testing is that it takes time and sometimes it is hard to reach an exact point in the code. But the method who uses it doesn't work properly, and you cant find the cause easily. because you have passed it a while ago.

Simply by calling the method in Immediate Window just after writing it, you probably had found the problem:
MyNamespace.MyClass.GetAllSubTexts("Sam")
Count = 5
    [0]: "S"
    [1]: "Sa"
    [2]: "Sam"
    [3]: "a"
    [4]: "am"
You see, the 'm' is not included. So if you change the outter loop to continue to last index, it is solved.

By using TDD and unit testing practices you may find yourself wasting your time writing unit tests. but at least you can manually unit test your individual methods, specially those who contain complicated algorithms, before they cause problems.