[Tutor] Law of Demeter example request
Sean 'Shaleh' Perry
shalehperry@attbi.com
Wed, 26 Dec 2001 20:33:55 -0800 (PST)
On 26-Dec-2001 Timothy Wilson wrote:
> Hi everyone,
>
> I'm looking over the early version of Bruce Eckel's _Thinking in Python_
> and I've got a question about the Law of Demeter, or as Bruce puts it,
> "Don't talk to strangers."
>
> I *think* I get it, but it would be great if someone would post a brief
> example illustrating the concept. Preferably, the example should show
> the same short program in two versions, one obeying the law and 2nd
> ignoring it.
>
class MoneyJar:
def __init__(self, value):
self.__value = value
def addMoney(self, value):
self.__value = self.__value + value
def subtractMoney(self, value):
self.__value = self.__value - value
def getTotal(self):
return self.__value
This class has one variable: __value. It is accessed by 3 methods.
class MoneyJar:
def __init__(self, value):
self.value = value
This too has one variable. However the only way to access it is directly.
jar = MoneyJar(10) # start with 10 units
jar.value = 5 # steal 5 units
Without a method in the middle the client can do anything to your class.
jar.value = "5 dollars"
amount = jar.value
subtotal = amount - (amount * tax)
What happens when jar.value is not a number? Using methods lets you define how
each item is accessed.
That was the safety aspect. However the total gains are less obvious. What if
you need to keep a running register of each transaction.
def addMoney(self, value):
self.register.addTransaction(addition, value)
self.__value = self.__value + value
def subtractMoney(self, value):
self.register.addTransaction(deletion, value)
self.__value = self.__value - value
easily done. Without the methods it is up to the client to remember to call
the register functions each time. Then you add a database, then there are two
other programs trying to read the jar at the same time, ..... as you can see a
little design up front saves you in the end. Safety is the obvious gain from
not talking to strangers, but there are many others.