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
}
}