Marcus Goldfish <magoldfish <at> gmail.com> writes:

> This raised another design issue for me, tho', regarding property
> validation.  In C#/Java, I would typically do validation in all of my
> setter methods, but is this really pythonic?  It seems OO--
> encapsulation-- but also seems to be one of the biggest wastes of
> coding time & typing in those languages.

I wouldn't validate unless there's some subtle (hard to detect) bad
behavior that might catch people off-guard and unless I'm dealing with an
untrustworthy and potentially malicious data provider (in other words, 
the user :)). Even then, it might be better/easier to use catch exceptions 
than to validate in advance.

Let's say we take your example and feed a list to it as a number. It will
crash even without the validation. There's nothing subtle about it, and 
it's good enough "validation" for me. 

If you drop the validation and feed it a number larger than 99 or lower
than 0, it will work just fine, even though it's going beyond its stated
intended use. In fact, the validation makes it *less useful*, because it 
wouldn't permit the user to use the class to its full capabilities. 
Perhaps the user doesn't want to feed your class with numbers, but with 
some objects which mimmick part of the integer behavior 
(http://docs.python.org/ref/numeric-types.html), but not the comparison to an
integer. The validation makes that impossible too. That sounds
a bit useless in this particular fantasy case, but there are plenty of other
cases where it's very useful.

Regarding the integrity of the class: if you prepend _ or __ to internal
attributes/methods, users of your class know that they're not supposed to mess
around with them. They *can*, but from that point on, it's no longer your
responsibility to protect them from themselves. Python works on the assumption
that programmers are responsible adults :).

Yours,

Andrei


_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to