This post originated from an RSS feed registered with Agile Buzz
by James Robertson.
Original Post: Law of Demeter and Smalltalk
Feed Title: David Buck - Blog
Feed URL: http://www.cincomsmalltalk.com/rssBlog/buck-rss.xml
Feed Description: Smalltalk can do 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.
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:
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.