13.07.2015 Views

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

Smalltalk Best Practice Patterns Volume 1: Coding - Free

SHOW MORE
SHOW LESS
  • No tags were found...

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Interesting Return ValueWhen should you explicitly return a value at the end of a method?All messages sends return a value. If a method does not explicitly return a value, the receiver ofthe message is returned by default. This causes some confusion for new programmers, who may beused to Pascal's distinction between procedures and functions, or C's lack of a definition of thereturn value of a procedure with no explicit return. To compensate, some programmers alwaysexplicitly return a value from every method.The distinction between methods that do their work by side effect and those that are valuable forthe result they return is important. An unfamiliar reader wanting to quickly understand theexpected use of a method should be able to glance at the last line and instantly understand whethera useful return value is generated or not. Therefore:Return a value only when you intend for the sender to use the value.For example, consider the implementation of topComponent in VisualWorks. Visual componentsform a tree, with a ScheduledWindow at the root. Any component in the tree can fetch the root, bysending itself the message "topComponent". VisualPart (the superclass of interior nodes andleaves) implements this message by asking the container for its topComponent:VisualPart>>topComponent^container topComponentScheduledWindow implements the base case of the recursion by returning itself. The simplestimplementation would be to have a method with no statements. It would return the receiver.However, using Interesting Return Value, because the result is intended to be used by the sender, itexplicitly returns "self".ScheduledWindow>>topComponent^self<strong>Coding</strong> <strong>Patterns</strong> page 139 of 147 9/30/2006

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!