[Newbies] Should all methods return a value?
Ron Teitelbaum
Ron at USMedRec.com
Tue May 9 11:59:38 UTC 2006
> From: Charles D Hixson
> Sent: Tuesday, May 09, 2006 1:16 AM
>
> I know that in some languages this matters, and in others it doesn't.
If a method doesn't explicitly have a return value it will return self, but
you should never count on that, small changes to the method will have a
tendency to break your code. Especially when someone decides that the
method should return something like true or false.
If in your code you really want "self" back from a method you can protect
yourself from this problem by adding ; to the end of your method call.
For example:
aFireman putOutFire
may return nothing in which case the following would work since it returns
self.
aFireman putOutFire cleanUpMess.
But if someone decides that putOutFire should return #smokeDamage then you
would be in trouble. So it's better to write the code
aFireman putOutFire; cleanUpMess. This says send the next message to the
receiver object of the previous message and it translates as
aFireman putOutFire.
aFireman cleanUpMess.
And if you haven't guessed
aFireman putOutFire; cleanUpMess; driveBackToStation. Works too.
Also sometimes what is returned can get in the way and if you really need to
return self you should add the following.
aFireman putOutFire; yourself. This way you could guarantee that the right
object "self" ends up where it should.
For example
aFireStation medalCandidates add: (aFireman putOutFire; yourself).
This makes sure that "self" is returned and changes to the implementation of
putOutFire will not hurt your code.
This is especially useful in collections, since add returns the object that
was added and not the collection.
aCollection := aCollection add: aFireman
would set aCollection to aFireman, not what was intended.
But
aCollection := aCollection add: aFireman; yourself.
Returns aCollection with an additional fireman in it.
Hope that helps!
Happy Coding!!
Ron Teitelbaum
President / Principal Software Engineer
US Medical Record Specialists
Ron at USMedRec.com
More information about the Beginners
mailing list