Thursday, February 26, 2009

Fluent interface for argument validation

I was fiddling around a bit with a fluent interface for validating method-arguments, it looks kind of promising…

    Public Class Foo
        Public Sub New(ByVal bar As String, ByVal baz As Integer)
            Ensure.ThatArgument(bar).IsNotNull()
            Ensure.ThatArgument(baz).IsInRange(1, 10)

            ' The argument can be named to for better exception messages...
            Ensure.ThatArgument(bar).Named("bar").IsNotNull()
            Ensure.ThatArgument(baz).Named("baz").IsInRange(1, 10)
        End Sub
    End Class

Using generics also makes the intellisense really helpful, for example the “IsInRange”-validation only shows up for IComparable(T)-types.

No comments:

Post a Comment