I was recently implementing an Orchard module and needed to read out a CSV file. Every line in the file contains a username and an email, with a ; in between. I read out the lines and create a User object.

I used this simple piece of code:

using (var reader = new StreamReader(stream)) {
    var line = reader.ReadLine();
    while (line != null) {
        var parts = line.Split(';');
        if (parts.Length != 2) {
            continue;
        }

        var user = new User {
            UserName = parts[0],
            Email = parts[1]
        };

        result.Add(user);
        line = reader.ReadLine();
    }
}

return result;

Can you spot what is wrong? Never mind the position of the opening curly braces, which is an Orchard convention.

The issue is here:

if (parts.Length != 2) {
    continue;
}

Because I’m not reading in the next line, my while loop is infinitely looping. An easy to fix error:

if (parts.Length != 2) {
    line = reader.ReadLine();
    continue;
}

The point I’m getting to is: how soon did I notice this?

Thanks to unit testing, I had a quick feedback loop and immediately saw my test was hanging. Compare this to how long it would have taken me to build, navigate to the correct page, select the file on my PC, watch as nothing happens, and then start debugging/investigating.

Just a quick example of how, certainly for me, writing tests does make me more efficient and speeds up my development. And when it doesn’t, it gives me more security when changing code later.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.