[Tutor] Why do I not get an error when I mistakenly type "humdrum.sigh_strenght" instead of the correct "humdrum.sigh_strength"?
Alan Gauld
alan.gauld at btinternet.com
Sat Jan 23 20:20:18 EST 2016
On 23/01/16 09:30, Cameron Simpson wrote:
> Alan will take you up on doing purer OO practices in Python.
In pure OO objects should only expose methods and the data
attributes should only be there to support the methods.
As such, nobody outside the object has any need to know
anything about it. And if you have data attributes that
no method uses that's a warning that they maybe are in
the wrong place! Likewise a class with no methods maybe
should just be a dict or tuple?
In the real world of course many objects exist primarily
as data stores - especially in business type apps. But
the principle remains that it's a very suspicious anti-pattern
to see code like:
anObj = myClass(...)
anX = anObj.X
anX = someFunc(anX) # alarm bells here
anObj.X = anX
This strongly suggests that there's a bit of functionality
that should be inside myClass as a method going on inside
someFunc().
And of course someFunc may be a series of inline statements,
it might not be so conveniently evident as a function call.
So as a class designer, if a user of your class (who might
be yourself!) insists that they need a setX style method
or wants public write access to an attribute you've got
to ask the question why? There is a strong chance they
really need a new method instead.
One of the features of OO programming is that large
monolithic algorithms/functions often get split into small
chunks distributed over several classes.
Finally, if you are really concerned about data access
control (but you have to consider why, and how big
a risk it is really) then don't forget you can define
properties in Python, which can be read-only, write-only,
or both. (Of course, in Python it's never bulletproof,
but it requires deliberate vandalism to subvert it.)
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos
More information about the Tutor
mailing list