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
Next Post
Cheatsheets  20 Sep 2006
Prior Post
What makes a Professional Developer?  25 Jun 2006
Related Posts
The Liskov substitution principle goes both ways  21 Mar 2020
Avoid hardcoded wait times  26 May 2018
Guaranteed Progression  19 May 2018
Prefer declarative method names  03 Feb 2018
Using Premeditation  27 Jan 2018
With Relocation  20 Jan 2018
Using Consolidation  13 Jan 2018
Using Semantic Types  06 Jan 2018
Using Extension Methods  30 Dec 2017
Error Methods  25 Nov 2017
More smart-code posts »
July 2006