Back to Top

Friday, December 12, 2008

Nice validation technique

Reading the Paint.NET blog I found this post about parameter validation. It is a very cool one for at least three reasons:

  • Makes the code more readable. Making the code such that readers can infer (correctly!) what the code does without additional comments is very useful.
  • Makes the code shorter.
  • Can be easily adapted into any OO language (the examples are given in C#, but it is trivial to port it over to Java for example).

The method itself consists of creating a Validator class with methods named intuitively (like isNull, isNotNull, isInRectangle, etc) that can be chained, so that you can write something like this:

  .isInRectangle(p, rect)

Now you can either throw exceptions individually, or accumulate them and throw them together. A very nice technique indeed.


Post a Comment

You can use some HTML tags, such as <b>, <i>, <a>. Comments are moderated, so there will be a delay until the comment appears. However if you comment, I follow.