[Newbies] Should all methods return a value?
Bert Freudenberg
bert at impara.de
Tue May 9 08:40:13 UTC 2006
Am 09.05.2006 um 07:16 schrieb Charles D Hixson:
> I know that in some languages this matters, and in others it doesn't.
> E.g., in C if you return a value, the temporary must always be stored
> when the function is called, but in other languages it can be ignored,
> and in some languages if you don't intentionally return a value, the
> system will automatically create a value (usually nil) to return
> for you.
>
> Eiffel make a big deal about separating Commands from Queries, with
> very
> strict rules about which kinds of routines can do what kind of things.
>
> Presumably Squeak (and Smalltalk) is flexible here...but I haven't
> seen
> it documented anywhere.
All you ever do in Smalltalk is send messages to objects, and maybe
assign the returned object to a variable. There aren't even control
statements (you can look up the ifTrue: method in the browser). When
you dig deeper into that you'll discover the beauty of this simple
approach :)
Since simplicity is paramount, we do not distinguish between methods
that return something or methods that do not. This also would imply
that the sending object knows in advance whether the particular
message you send will return something or not.
This weak coupling of sender and receiver (sometimes called late
binding) also is essential. You can send any message to any object,
but it's always the receiver who chooses how to respond to the
message. Indeed, even the terminology reflects that - we strongly
distinguish between messages and methods, you cannot "call a method",
you can only "send a message" which in turn "activates a method".
To return to the return value (pun intended), the *sender* of a
message of course knows whether it will use the object returned.
That's why the compiler issues slightly different bytecodes in the
sending method, but that's mostly for balancing the stack, and a bit
for performance.
And about separating commands from queries - this still is a good
rule of design, but we do not build it into the language. A nice
article about how this fits into OO design is "Tell, Don't Ask":
http://www.pragmaticprogrammer.com/ppllc/papers/1998_05.html
- Bert -
More information about the Beginners
mailing list