[Tutor] Law of Demeter example request

alan.gauld@bt.com alan.gauld@bt.com
Thu, 27 Dec 2001 13:55:06 -0000


> and I've got a question about the Law of Demeter, or as Bruce puts it,
> "Don't talk to strangers."

OK, The other way of stating it is that objects 
should 'do it to themselves'...

For example, if we have a diary object that contains 
a list of appointments. Maybe the diary has a method

moveAppointment(self, Appointment, deltaTime)

We could implement it like this:

def moveAppointment(self, Appointment, deltaTime):
    App = self.Appointments.find(Appointment)
    T = App.getTime()
    T = T + deltaTime
    App.setTime(T)

Or we could do:

def moveAppointment(self, Appointment, deltaTime):
    App = self.Appointments.find(Appointment)
    App.changeTime(deltaTime)

Thus the diary knows how to manage appointment objects 
but leaves the Appointments themselves to manage the 
details like their time etc.

Of course we'd be in an even worse state if the diary 
was setting the Appointments internal state variables 
directly! But no one would be daft enough to do that, 
would they? ;-)

It means building more low level methods but the 
end result is much more resilient to change and 
the low level objects more liable to be reusable.

> example illustrating the concept. Preferably, the example should show
> the same short program in two versions, one obeying the law and 2nd
> ignoring it.

I've tried...

Alan G.