February 10, 2009

Mocking

An old article by Roy Osherove that looks at the popularity of different mocking frameworks. Rhinomocks comes out ahead, but it is interesting to see what other mocking frameworks are out there and their approximate usage.

Choosing a mock Object Framework

February 8, 2009

Disposable Discoveries

A few days ago, there was a discussion at work about the using statement. The question was around what exactly the code snippet below gets transformed into

using (FileStream fileStream = new FileStream(sourceFile))  
{  
    // do something  
}

It was generally agreed you would get something like this.

FileStream fileStream = null;  
try  
{  
    fileStream = new FileStream(sourceFile);  
    // do something  
}  
finally  
{  
    if (fileStream != null)  
    {  
        fileStream.Close();  
        fileStream.Dispose();
    }  
}

The focus was on whether the Close() method gets called and if it would be better to just call everything explicitly to be sure. It turns out the Close() method is called, but not by the using statement. In this case, the FileStream inherits from System.IO.Stream which will call Close() from within its Dispose() method. A number of other "base" classes will also do the same.

February 2, 2009

Method Exit Points

Method exit points are important in many ways. Under the assumption that multiple entry (goto) is not even worth talking about, the focus is on where you exit your method.

When going with a Single Entry, Single Exit you get a few advantages. First, you know that the full length of the method will always be followed. In older languages, this is a good thing. With newer languages, not as much of an issue. Regardless, closing out or handling things the exact same way each time can be quite useful. This can make things safer as you won't be exiting at midway through a method when a file was not closed properly or exception handled. It also allows you to follow the return value through the full scope of the method which can give you a better idea of what each point is returning.

Single Entry, Multiple Exit can lead to more clear and readable code. The best practice is to assume failure and prove otherwise. This leads towards building guard statements with immediate returns, rather than building an onion backwards with condition statements. It also doesn't carry any unnecessary baggage. The check failed? Then why continue?

 
Copyright © CodeCuriosity | Theme by BloggerThemes & frostpress | Sponsored by BB Blogging