High quality input validation is essential to many, if not all systems that we write. It doesn’t matter whether we’re validating user input in a WPF or Silverlight application, checking data transfer objects passed into a service layer or verifying the information in a JSON packet submitted by REST, validation is essential.
Lately, I’ve been working with a bunch of code that looks like this:
This code works - but it is ugly. The code is verbose and repetitive - the mechanics of building
items and adding them to the results list swamp the actual checks being made.
Inspired in part by an Ivan Towlson presentation at Microsoft TechEd 2011 in New Zealand, I’ve got a prototype going in Visual Studio 2010 that looks like this:
How on earth does this work?
ValidationContextclass provides an ambient context for validation that gathers up validation results in the background, without any need to pass around the list itself.
Leveraging the new dynamic keyword in C# 4 allows the
ValidationContextto behave as though it has a method for each property declared on
myPerson. The named parameters passed to these dynamic methods specify the requested checks.
What do you think? Does this qualify as evil code, or merely expressive?
Should I turn this prototype into an actual library and make it available for download?