Model Validation

I got into an interesting conversation with my friend and coworker David Morton regarding model validation. Where does it belong? I have seen examples of self-validating models, validation as a service, and even UI-only validation.

Perhaps it depends on the implementation, but if you follow SOLID principles, I think you will at least end up with a validator type that performs the validation, either as a strategy on the model or a separate service.

We started with self-validating anemic domain models on my last project. That’s possibly an oversimplification, but it worked well for those models that were truly used in a CRUD-only manner. More complex models quickly became difficult to maintain, and as part of the refactoring, we split out the validation duties into their own class and now provide validation through the service layer for the client. This acts as a sort of anticorruption layer (Evans).

I really like this approach best. You can still call the validation from the client before sending, and your model may continue to focus on it’s real job. What are your thoughts or preferred approaches?

Advertisements