[Tutor] Class access rules

Alan Gauld alan.gauld at yahoo.co.uk
Mon Mar 7 18:55:52 EST 2022


On 07/03/2022 23:17, Phil wrote:

>> methods should do all the work and the attributes are only
>> there internally to support those methods. 

> My LED class uses a boolean state attribute, if the state is True then 
> the LED is filled with the on_colour. I had in mind creating on and off 
> methods that set the state rather then directly setting the state 
> attribute. From what I understand setting the state attribute directly 
> is good practice.

Actually I'd advocate having on/off (and maybe toggle) methods.

Those are the things you actually do with a LED.
How you implement those methods may or may not involve
internal state. But I have never in practice asked a LED
for its state (unless you count looking at it to see if
it is lit I suppose, but that should then become an isLit()
predicate)

Focusing on the internal state attribute leads to a data
centric view of the object rather than its operational interface.

But notice how a single state attribute now results in 4 operations.

You could just provide two: getState/setState, but then you move
the understanding of how the LED operates to the user of the LED
rather than it being intrinsic to the LED itself. Remember
the OOP axim, "objects do it to themselves"(*)

(*) Coad & Nicola in their book "Object Oriented Programming"
circa 1993.

-- 
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