From: Tom Wardrop Date: 2010-12-31T12:08:23+09:00 Subject: Where To Put Validation Logic? This is probably a question you could put to any programmer who writes object-oriented code. I'm developing a Mongo object mapper for Ruby, inspired by Candy's write-on-set approach. I'm currently still in the planning phase, trying to work out the scope of the project and the most appropriate interface. One question I now find myself asking, is whether to include validation helpers, and if so, where should they reside? In the model, or in the controller? The answer I guess also depends on the scope of the project. Will the mapper act as a foundation for all models (like most mappers), or will it be more like a tool that models will simply use, if they have to - something I'm still undecided on, but which I'm hoping this thread may help me with. While validation serves as a means to ensure the integrity of data, it can also serve as a means to validate user input at the application level. If you look at validations as a means to ensure data integrity, then naturally, such logic should reside in the model; the data layer of the application. On the other hand, looking at validation as a means to validate user input and interactions with the UI, you would think the controller would be the better fit. When you think about it, you're really dealing with two types or levels of validation: user-level, and data-level. A good example that demonstrates this, is assume you had an application that can accept a home phone number, a work phone number, and a mobile/cell phone number. No field is mandatory, but at least one phone number must be given. You could call this multi-field validation. In theory, the data layer of your application shouldn't give a damn about whether or not at least one phone number is set. All the data layer should care about is whether it has a valid phone or not. How I see it, such "multi-field" validation can be classed as general application logic which should be the responsibility of the view/controller, not the data layer, who's only responsible should be persisting the data. Sadly, I don't know the right answer here, hence why I've come to this forum. Hopefully some of you have some thoughts or opinions to share on this matter? Remember, one the main reasons for bringing up this topic, is because I'm writing a Mongo object mapper that writes to Mongo when a field is set, hence such multi-field validation can't easily be achieved. This made me challenge my understanding of validations and which part of the application should be responsible for them. -- Posted via http://www.ruby-forum.com/.