|
|
|
|
|
by gecko
5538 days ago
|
|
There's a solution in Smalltalk that I'm wondering why no one's brought to Ruby. In applications where this pattern is useful, there's a class, Null, with the singleton null (in contrast to UndefinedObject and its singleton nil). nil raises an exception, but null simply eats all messages sent to it, much like the maybe monad you listed. This makes it really easy to mix and match the two paradigms in your code: in places where it's okay for the object to just eat messages, you return null. In places where no value is a real error, you return nil. Either value can be converted to the other with a one-line statement, and to existing code, null looks like nil when queried (i.e., isNil returns true, ifNil: and ifNotNil: and friends behave as if null were nil, etc.). Seems as if writing a similar tool for Ruby would be trivial. |
|
With #try et al it's made obvious at the point the message is sent whether it'll be swallowed by nil (and that you're fine with this). To me this seems safer than having two classes of entities knocking round, one swallowing messages and one not, and no way to tell at a glance which is which.
(I've not used Smalltalk btw, so apologies if I've misunderstood...)