[Edu-sig] Re: Best approach to teaching OOP and graphics

Beni Cherniavsky cben at users.sf.net
Fri Apr 1 01:53:45 CEST 2005


Dethe Elza wrote:
> On 27-Mar-05, at 2:04 PM, John Zelle wrote:
> 
>> There is a good reason for these traditional guidelines, that is to 
>> make the abstraction you are defining independent of its 
>> implementation. Down the road, I might want to change the internal 
>> representation of color, or remove or rename the color instance 
>> variable. If existing code exploits this internal feature of a class, 
>> then changing the implementation may break code that uses it. So this 
>> is bad design --- in most languages.
>>
>> And yet, this is common in Python. Why? Because of Python's dynamic 
>> nature I can still change the implementation should I choose to and I 
>> can preserve the old abstraction (interface) using getAttr and setAttr 
>> magic. I can't do that in most other languages, which is why they tend 
>> to use getter and setter methods.
> 
 >
 > Or more recently (and cleanly) by using properties (new style classes
 > only).
 >
 > The *only* reason that other languages promote the use of method calls
 > over direct property access is because they don't have properties.
 > Without properties it is very
 > difficult to go in and modify the implementation without changing the
 > interface if you start by using attributes, but in Python that problem
 > just doesn't exist.
 >
I will dare a stronger formulation:  Littering trivial getters/setters is 
unpythonic because it is vebose and ugly.  This is reason enough not to write 
them, whether we have properties or not.  Given this axiom, Python provides 
properties to solve a need *resulting* from not calling getters/setters 
exlicitly - it is secondary.

I think teaching students to actively detest code that with huge redudant 
repetitive piles of redudancy repeated all over is more important than 
teaching them any single guideline.  The guidelines are tools invented for 
writing better code, nothing more.

> There are still times when you don't want to expose attributes directly, 
> but getters and setters don't help you there either.  For example, if 
> both myObj.x and myObj.y must be changed in synch to stay valid, then 
> they should be set via myObj.setXandY(x,y) not myObj.x = newX, myObj.y = 
> newY.  But this is a design problem not a language problem.
> 
myObj.xy = (x, y)

Rule of thumb: use tuples where you typically change all members together. 
Use mutable objects (lists/dicts/objects with attrs) where you frequently 
change individual members.

-- 
Beni Cherniavsky <cben at users.sf.net>, who can only read email on weekends.


More information about the Edu-sig mailing list