Creating Your Own Using Statement
This is a C# feature only, so sorry to all you VB guys (and all the Boo guys are laughing at me for having to go to such great lengths to do trivial things).
The idea here is to wrap a piece of code with behaviors, and allow you to act upon certain things (such as exception) when they happen.
For instance, let us take a transaction handler. The default way to handle a transaction in .Net is this:
using (ITransaction tx = Context.BeginTransaction()) { //do work tx.Commit(); } |
You have to call the Commit() method at the end of the using block, or else the changes you made will be rolled back. It is very easy to forget this, unfortunately.
Here is a better way:
With.Transaction(delegate { //do work }); |
This code block is wrapped in a transaction, and it will automatically commit at the end, and more importantly, it will automatically will rollback any changes if an exception has occurred. This is much simpler than the alternative, but it is still not the interesting part. The interesting part is that we can extend this to other areas.
For instance, take this example:
With.ExceptionPublishing(delegate { //do work }); |
If an exception happens within this block, it will be publish and then re-thrown, writing the code is as simple as this:
public static class With { public static void ExceptionPublishing(Proc method) { try { method(); } catch(Exception exception) { ExceptionPublisher.Publish(exception); throw; } } } |
I saw something very similar to this in Oren Ellenbogen talk, but he used parameterized delegates to pass the required objects to the code. I am a great believer in Context Based Programming, which saves the need for parameters. This really nice thing about this is that it allows you to know whatever it was an exception that cause you to exit this code block or no.
This is my main complaint against using() blocks in general, and it was the reason that I remove IDisposable from Rhino Mocks (way too many problems). Now I will need to consider adding it back again.
Comments
Comment preview