Object Oriented Programming

Law of Demeter and Smalltalk

January 4, 2004 14:31:09.116

The Law of Demeter states that:

Within a method, messages can only be sent to the following objects:

  • A parameter of the method, including the enclosing object (this or self);
    • For pragmatic reasons: a global object;
  • An immediate part object (computed or stored):
    • An object that a method called on the enclosing object returns, including attributes of the enclosing object;
    • An element of a collection which is an attribute of the enclosing object;
  • An object created within the method

In general, this is good advice for object oriented development. When it comes to Smalltalk, though, it seems too restrictive. When all your conditional and looping constructs are implemented with messages, the Law of Demeter becomes excessively strict.

Consider the following code:

Employee

= anEmployee
   ^(self name = anEmployee name)
      and: [self employeeID = anEmployee employeeID]

The Law of Demeter would state that the first = is ok (since the receiver is "an object that a method called on the enclosing object returns") but the and: message is bad because it sent to the result of another message send.

If I was to strictly follow the Law of Demeter, I would have to re-write this as:

Employee

= anEmployee
   ^(self nameMatches: anEmployee)
      and: [self employeeIDMatches: anEmployee]

nameMatches: anEmployee
   ^self name = anEmployee name

employeeIDMatches: anEmployee
   ^self employeeID = anEmployee employeeID

How about another case. Should this be allowed?

Object

printOn: aStream
   | title |
   title := self class printString.
   aStream nextPutAll:
      ((title at: 1) isVowel ifTrue: ['an '] ifFalse: ['a ']).
   aStream nextPutAll: title

The messages "printString", "at:", "isVowel", and "ifTrue:ifFalse:" all break the Law of Demeter.

You'd have to re-write it as:

Object

printOn: aStream
   | title |
   title := self title.
   aStream nextPutAll:
      ((self startsWithVowel: title) ifTrue: ['an '] ifFalse: ['a ']).
   aStream nextPutAll: title

To me, this seems excessive. If the Law of Demeter made an exception for primitive types and messages, it would probably be ok. As is, things that would be perfectly fine in other languages would be illegal in Smalltalk. It just doesn't feel right.