| Exploring Solution Spaces © Copyright 2003-2006, by C. Keith Ray | ||||||||||||||||||||||||
|
Archives
Subscribe |
2004.Jan.07 Wed One of the neato things about Python is returning a small number of multiple values from a method is easy. For example, finding the elements that are shared by two collections/lists [hope I got the syntax right]: beforeNotAfter, afterNotBefore = foo.findNonOverlappedElements( before, after ) # do stuff using beforeNotAfter # do stuff using afterNotBefore Alan Knight says the Smalltalk "moral equivalent" to this uses a block (my paraphrasing here):
foo findNonOverlappedElementsOf: before and: after
doing: [ : beforeNotAfter : afterNotBefore
"do stuff to beforeNotAfter".
"do stuff to afterNotBefore" ].
Coming from a background of C/Object-Pascal/Objective-C/Java/C++, it's hard for me to think of reasons to do a Python-style multiple-return; instead of one method that returned two values, I'd write two methods, or single method that returns a data-structure or has output-parameters. And, unfortunately, Objective C, Java, etc., don't make "blocks" easy. Though there is a dialect of Objective-C that has blocks, it's not the dialect supported by gcc and Apple. The other aspect of the Smalltalk solution here is "tell, don't ask". We tell 'foo' to find the non-overlapped elements, and we tell foo what to do with the resulting lists of elements (execute our block). This forces a certain cohesion to our code. The Python example is violating the spirit of the Law of Demeter, if not the actual Law (1) because we ask and then work the results of what we asked. footnote 1: Law of Demeter (LoD) is really just a guideline that is particularly questionable when collections are involved. |
|||||||||||||||||||||||