Monday, September 14, 2009

Try Finally Pattern

This kind of coding style seems to be very common:

public void DoSomething(string filename)
{
var file=File.OpenText(filename);
if(! some_condition)
{
file.Close();
file.Dispose();
return;
}
//Do some other stuff
file.Close();
file.Dispose();
}
The problem here (as you can see) is that we are repeating some lines that
should be executed either everything is ok or if something is wrong.
(A violation of DRY)

We can refactor this code like this:
public void DoSomething(string filename)
{
try
{
var file=File.OpenText(filename);
if(! some_condition)
{
return;
}
//Do some other stuff

}
finally
{
file.Close();
file.Dispose();
}
}

Now no matter what will happen in our try block , finally block
will always run.

In this particular case since we are using an IDisposable class
(FileStream)we can make our code even more readable and
maintainable like this:

public void DoSomething(string filename)
{

using(var file=File.OpenText(filename))
{
try
{
if(! some_condition) return;
//Do some other stuff

}
finally
{
if(file!=null)file.Close();
}
}

}



No comments: