As I mentioned on Google+ the other day after listening to this episode,one of the best things that Smalltalk offered with its optional system was/is the ifNil:/ifNotNil: and isNil:/isNotNil messages ( Nil is an Object in its own right, and offers negative variations of the four messages) .

The if variations take blocks meaning you can write code like:

(customerManager findCustomerNamed: 'Tor') ifNotNil: [ | cust |
  cust increaseLevelBy: 5].

The block gets executed ONLY if the result is not nil/null, and the value is passed along as a parameter to the block/closure.

No NullPointerExceptions, no temporary variables.


On 6/06/12 8:28 AM, Graham Allan wrote:
My 0.02c, FWIW.

I have found using a variant of the Option notion quite satisfying in some use cases. In my case we use Nat Price's Maybe for Java, but it's essentially equivalent[1]. (I'll use the term Option here for consistency, though the API of the two things are not the same)

What I have found is it tends to be more useful as return values rather than parameters. For example, it is possible to have methods where they can be invoked correctly, in the right state, but still have no 'correct' return value. As a trivial example consider a Person class which contains an optional middleName property. Throwing an exception when you ask for the middle name in this case would be really unfriendly, since nothing exceptional has occurred. You could return null, but it could be easy to forget to check. Having the compiler tell the callers that they may not get something they're expecting, rather than it being a runtime null value has been quite elegant.



--
You received this message because you are subscribed to the Google Groups "Java 
Posse" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/javaposse?hl=en.

Reply via email to