Tuesday 25 November 2014

Guard yourself

It's often handy to have "Guard" logic in your code to validate expectations. It's an integral part of the code and is generally used to throw exceptions when something does not meet expectations. The bulk of the Guard code would live at the beginning of methods to validate arguments, but in theory it could be used anywhere for anything.

There are a large number of open source libraries that provide this functionality (try a nuget search for guard). While it's always nice when somebody else has already done the hard work, in this case the work isn't really that hard. So you might, for reasons of flexibility, want to write your own. Here is a very simple example that I think gives full flexibility and allows you to add any bespoke checks you may need.

First we have a very simple static class that is the heart of the implementation.


I told you it was simple! This would allow you to validate anything and throw any exception. I've gone for "Ensure.That()" so there is less likelihood of naming conflicts and I really like how it reads, "Ensure that ...".

Next, I've created another very simple static class with the validations.


This is a very small subset of the methods you might require (although it would probably cover the bulk of your validations). You would be able to add as you go. Obviously you don't need to use methods from this class to do the validation but it is handy having everything in one place.

Here is an example of it in action


Very simple and again I like the way it reads, "Ensure that value is ...".

Tuesday 18 November 2014

Small Things - Recursive Lambda

In hindsight recursive lambda is obviously possible, but it's nothing I've ever come across and nothing I'd ever tried. I think it has a very high coolness factor! But not entirely sure how often it would be useful.

Anybody have any interesting examples of actual use in the wild?