Friday, November 19, 2010

Validation! So simple, yet so complicated (part 1)...

Guess this is going to be a two parter! in part I, I will be discussing how to protect your business logic by actively throwing exceptions when validating. in part II I will discuss the standard, more passive validation techniques not using exceptions.

When dealing with any class, you have values, and those values will be stored in a class within member variables. Those variables are usually basic data types, like strings, dates, integers, etc. For almost any member variable, there is a subset of all the potential values that datatype can contain that are actually valid.

Determining if a given value is within this subset of valid values is what validation is all about. In this blog post I will discuss an aspect of validation I do not believe is very clear; when to validate.

What I mean when I say "when to validate" I mean, when do you notify other parts of the code that the provided value is not within the acceptable subset of the provided data type. validation can occur:


When the value is assigned
This is usually done via a property or method that encapsulates the variable. The code attempts to provide a value to the class via it's property, and the property checks if its an acceptable value. If it is not an acceptable value, the code throws an exception describing why the value is invalid. Numerous objects use exceptions to reject invalid values. For example, when dealing with an index based collection, passing a negative index, will result in an IndexOutOfRangeException being thrown.

this sounds like a great answer for validation,  but it should be used as a last resort or make sure that your classes member variables are always within an acceptable value range. Methods the receive parameters or properties that are used in mission critical classes should always check if the values outside of what you'd expect be handled in this way. I consider these types of validations as Active Validation. Below are a list of existing exceptions you can use for active validation:

*note* This type of validation should be considered your LAST line of defense. Why? the very definition of exception is that at that point in the code, you have an exceptional scenario, you can't complete what the code is attempting to complete! this is the only place you should be dealing with a validation issue with an exception.


No comments:

Post a Comment