[Tutor] What's the correct way to define/access methods of a member variable in a class pointing to an object?

Alan Gauld alan.gauld at yahoo.co.uk
Sat Sep 3 14:23:48 EDT 2016


On 03/09/16 18:17, Steven D'Aprano wrote:

> One classic example of the Law Of Demeter is:
> 
> "If you want your dog to come to you, don't talk to your dog's legs, 
> talk to the dog."

I love that, I've never seen it before but a great example.

> But sometimes the Law Of Demeter should not apply. Sometimes you are 
> expected to tinker with the internals of an object.
> 
> car = Car()
> # replace the engine with a bigger one
> car.engine = Engine("800 horsepower of throbbing nitro-fueled POWER")
> car.engine.inject(nitro=True)

Yep, although in that case I'd take the engine "out of the car"

engine = car.engine
engine.inject()
car.engine = engine

Of course in python(or Java) the last line is usually not needed
because we work with references to the real object
rather than copies...

Its not necessary to get the extra reference but for me I
like the code to reflect the intent as well as the need.
So by creating an external reference to the engine it reminds
me that I am tinkering with a different object to the car.

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