Very simple question, but I want to start using a consistent naming convention for validation methods and I can't think of the best way!
Do people tend to use IsDataValid() style? or are there any others that are more descriptive and meaningful?
Cheers
It depends what your validation method does.
If it returns a Boolean, then probably starting with Is
and ending with Valid
is a good place to start. Using is
for Boolean calls generally leads to readable code in if
statements.
If your validation method throws an exception, then I'd usually start the method name with something like Check
instead.
However, also worth considering (as methods should usually use verbs) is beginning the method name with Validate
. The Is
style is generally more applicable to properties.
As with anything involving naming conventions, there's no such thing as a right answer, but there's a lot of common problems with validation methods that lend themselves towards a certain approach, namely:
- If everything is OK, you typically only need the boolean status of the validation.
- If there are problems, you usually need to know details about the problem.
- You usually want objects to have similar approaches to validation.
One approach I've found to be useful is to have a seperate validator class for each model object I want to validate that implements a common IValidator
interface, usually with the following methods:
- A constructor that takes the object to be validated in.
- A property named IsValid(), that validates the object, returns a boolean, but stores specific errors in private variables so validation doesn't need to be recalculated when you do want the errors.
- A property named ErrorMessages, that validates the object (if it hasn't been validated yet), and returns a list of errors with the object.
This allows a pretty natural usage within your business logic:
BusinessObject obj = new BusinessObject();
// populate fields
BusinessObjectValidator objValidator = obj.GetValidator();
if (objValidator.IsValid) {
obj.Save();
} else {
foreach (var errorMessage in objValidator.ErrorMessages) {
// output message
}
}
Do people tend to use IsDataValid() style?
I typically use the 'Is' MethodName style when the method returns a single Boolean value. It is perfectly acceptable in terms of naming. A lot of times data validation is done within the Set of a Property rather than a method so in this case you don't need to change the property name to indicate it validates the data set on it.
Here is a link that gives some general naming guidlines which you might find interesting as well:
Naming Guidelines:
http://msdn.microsoft.com/en-us/library/xzf533w0(v=vs.71).aspx