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.

Comments

blog comments powered by Disqus
Next Post
Cheatsheets  20 Sep 2006
Prior Post
What makes a Professional Developer?  25 Jun 2006
Related Posts
Using Constructors  27 Feb 2023
An Inconvenient API  18 Feb 2023
Method Archetypes  11 Sep 2022
A bash puzzle, solved  02 Jul 2022
A bash puzzle  25 Jun 2022
Improve your troubleshooting by aggregating errors  11 Jun 2022
Improve your troubleshooting by wrapping errors  28 May 2022
Keep your promises  14 May 2022
When are you done?  18 Apr 2022
Fixing GitHub Authentication  28 Nov 2021
Archives
July 2006
2006