A common problem in any language is to assert that parameters sent in to a method meet your requirements, and if they don\'t, to send nice, informative error messages. This
Just as a contrast, this post by Miško Hevery on the Google Testing Blog argues that this kind of parameter checking might not always be a good thing. The resulting debate in the comments also raises some interesting points.
Alright guys, it's me again, and I found something else that is astonishing and delightful. It is yet another blog post referred to from the other SO question that Chris, above, mentioned.
This guy's approach lets you write this:
public class WebServer
{
public void BootstrapServer( int port, string rootDirectory, string serverName )
{
Guard.IsNotNull( () => rootDirectory );
Guard.IsNotNull( () => serverName );
// Bootstrap the server
}
}
Note that there is no string containing "rootDirectory" and no string containing "serverName"!! And yet his error messages can say something like "The rootDirectory parameter must not be null."
This is exactly what I wanted and more than I hoped for. Here's the link to the guy's blog post.
And the implementation is pretty simple, as follows:
public static class Guard
{
public static void IsNotNull<T>(Expression<Func<T>> expr)
{
// expression value != default of T
if (!expr.Compile()().Equals(default(T)))
return;
var param = (MemberExpression) expr.Body;
throw new ArgumentNullException(param.Member.Name);
}
}
Note that this makes use of "static reflection", so in a tight loop or something, you might want to use Rick Brewster's approach above.
As soon as I post this I'm gonna vote up Chris, and the response to the other SO question. This is some good stuff!!!