I’m really fussy about writing safe code, and I’m a sucker for neat tricks as well - so this deceptively simple idea from Ayende.com is doubly attractive.

The idea in this blog entry is to make it easy to expose an API that’s both semantic and safe for the caller.

So often an API requires that pairs of methods are called together - StartProcess and EndProcess or some similar situation.

But how do you ensure that both methods are called in pairs - too often, the answer is to rely on copious documentation and some strategic exception throwing.

The problem with this approach is that all it does is push the complexity away from the library developer and onto the consuming developer - the poor schlump trying to make use of the library.

The DisposableAction class (which is only possible because of the anonymous delegates supported in .NET 2.0) gives a simple and elegant way to ensure that the closing method will always be called.

This is entering my personal library of must have tricks today.


blog comments powered by Disqus