[Tutor] object attribute validation

Prasad, Ramit ramit.prasad at jpmorgan.com
Mon Feb 25 18:44:41 CET 2013


neubyr wrote:
> Thank you for your comments Steven.
> 
> Yes, I think I should remove property deleter in this case.
> 
> I would like to use this Person class in another class. For example, if Person class is 'model' in a
> small MVC-style web application, then where should I place my validation. A view form will be passing
> parameters to a controller which will create and write Person objects/models. Should the validation be
> in place at all three levels?
> 
> I am inclined towards adding integer validation in views, but I am not sure where should I add it in a
> controller class. Also, it's easy to add integer validation in view form (javascript), but what if I
> have a more complex format - X509 certificate or  some other file-type related validation? Is it OK to
> validate them only in property setter methods?
> 

Where I would place validation depends a bit on the project. As I see it there are two types of 
validation, simple and complex. Simple validation is something like "is this an int?" or "did
they fill in all parameters?" and should be done in the form(view). Complex validation is more of
a logical/business validation like "is using a blowhole a valid operation for Animal type Giraffe?" 
This can be done where you do an action (e.g. creating Person class) or in the class/module itself 
(controller). If you instantiate Person objects from various different places in code (assuming no 
code duplication) then I would either create a validation function or add it to the class, but if you 
only have one place where Person objects are created I would add the validation there with comments on 
validation rules or reference links.

I tend to favor validation functions where I can give all parameters and it can return either bool, 
or an appropriate error message. My use case is where objects do not usually need to change once 
created (i.e. I have all input in advance). If I thought the objects would change frequently, 
then adding the validation to the setter makes sense. You can also combine the two ideas by 
adding the validation to the setters and having a wrapper validation function that creates a Person
object and then sets the params (returning either the new object or error message). 


~Ramit


This email is confidential and subject to important disclaimers and
conditions including on offers for the purchase or sale of
securities, accuracy and completeness of information, viruses,
confidentiality, legal privilege, and legal entity disclaimers,
available at http://www.jpmorgan.com/pages/disclosures/email.  


More information about the Tutor mailing list