Why less emphasis on private data?

Bruno Desthuilliers bdesth.quelquechose at free.quelquepart.fr
Mon Jan 8 16:08:40 EST 2007


time.swift at gmail.com a écrit :
> Wow, I got a lot more feedback than I expected!
> 
> I can see both sides of the argument, both on technical merits, and
> more philosophical merits.  When I first learned C++ I felt
> setters/getters were a waste of my time and extra code.  When I moved
> to C# I still felt that, and with their 'Property" syntax I perhaps
> felt it more.  What changed my mind is when I started placing logic in
> them to check for values and throw expections or (hopefully) correct
> the data. That's probably reason one why I find it weird in Python

Python does have properties too. The point is that you can as well start 
with a plain attribute, then turn it into a computed one when (and if) 
needed.

> Reason two is, as the user of a class or API I *don't care* what is
> going on inside.

Very true... until you have a legitimate reason to mess with 
implementation because of a use case the author did not expect.

> All I want visible is the data that I can change.  The
> '_' convention is nice.. I do see that.  I guess my old OOP classes are
> hard to forget about.

Access restriction is not a mandatory part of OO. Of course, objects are 
supposed to be treated as "black boxes", but that's also true of a 
binary executable, and nothing (technically) prevents you to open it 
with an hex editor and hack it as you see fit... But then, you would not 
complain about strange bugs, would you ?-)

> I feel that the state of an object should be
> "stable" and "valid" at all times,

That's fine. Just remember that, in Python, methods are attributes too, 
and can be dynamically modified too. So when thinking about "object 
state", don't assume it only implies "data" attributes. Heck, you can 
even dynamically change the *class* of a Python object...

> and if its going into an unstable
> state - error then, not later.  That's why I like being able to protect
> parts of an instances state. If, as a provider of a calculation engine,
> I let the user change the internal state of the engine, I have no
> assurances that my product (the engine) is doing its job...

If you follow the convention, you are not responsible for what happens 
to peoples messing with implementation. period. Just like you're not 
responsible for what happens if someone hack your binary executable with 
an hex editor.

Welcome to Python, anyway.



More information about the Python-list mailing list