posts - 50, comments - 127, trackbacks - 6

My Links

News



View Marcin Celej's profile on LinkedIn

Archives

Post Categories

Transactional code pattern

In my job I have to deal with databases. When you do such things, there always is a need to do something transactionally. The pattern of doing something transactionally looks usually like this:

Transaction t = DB.BeginTransaction();
try
{
    // Do something

    t.CommitTransaction();
}
catch
{
    t.RollbackTransaction();
}

The code looks simple at a first glance but some people create variations of the above snippet. I checked code of my coworkers and found many mistakes in the transactions usage (I am responsible for frameworks in my project). Most often someone (who didn't wrote the code originally) didn't notice that there is something executed transactionally and inserted some code after the CommitTransaction() method call. When the code failed there was attempt to rollback already commited transaction.

.NET 2.0 helped to solve the problem. I introduced a method that takes a delegate as a parameter. The delegate points something that should be executed transactionally. So the above example looks like that now:

DB.DoTransactionally(delegate()
{
    // Do something
});

As you can see it is much simpler and there is much less chance to make a mistake. It's also much more readable (thanks to anonymous method). I also introduced overloaded version of the transactional method to allow easily to return some information from the delegate:

public decimal CalculateBalance()
{
    return DB.DoTransactionally<decimal>(delegate()
    {
        // Do something

        return 0;
    });
}

The above example uses generic method to indicate that the delegate inside should return some value. Then the DoTransactionally() method returns the value to make the code even easier.

My coworkers cannot make mistake now.

Print | posted on Sunday, February 19, 2006 7:26 PM |

Feedback

No comments posted yet.
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: