views:

49

answers:

1

Suppose I'm creating a class to validate a number, like "Social Security" in US (just as an example of a country-based id). There are some rules to validate this number that comes from an input in a html form in a website.

I thinking about creating a simple class in Python, and a public validate method. This validate returns True or False, simply. This method will call other small private methods (like for the first 'x' numbers if there is a different rule), each one returning True or False as well.

Since this is really simple, I'm thinking of using boolean status codes only (if it's valid or not, don't need meaningful messages about what is wrong).

I've been reading some articles about using exceptions, and I would like to know your opinion in my situation: would using exceptions would be a good idea?

+4  A: 

If an input is either valid or not, then just return the boolean. There's nothing exceptional about a validation test encountering an invalid value.

csj
`raise NeitherValidNorInvalidException('D:')`
Jon Purdy
Thats what I'm thinking of at first. Thats why Im asking for more opinions, maybe someone can see something I'm not aware of. Thanks.
Somebody still uses you MS-DOS
Well, to expand a bit further. Suppose I had a method that uses the value, say ErasePersonalIdentity(ssn), then it would be reasonable that ssn should be valid. If an invalid ssn were provided, then raising an InvalidSSNException would be appropriate. The point being, if an operation requires valid input, then an exception should be triggered when invalid input is provided. If an operation is validating input, then there is no exception.
csj
@csj is spot on. Remember, if you want an exception you can always `assert Validator.is_valid(ssn)`.
katrielalex