Jun 17, 2012

Just Maybe, Maybe - Pattern in Ruby

The original code I posted was flawed.  The gist below is modified and I think would work but it's not as clear as I'd like it to be.  I'll follow up on this soon.

I recently released a tiny Gem called JustMaybe.  This caused me to do more reading on the subject.  I ran across the If you gaze into nil nil gazes also into you post.  In the JustMaybe readme I sort of mention this but I wanted to express it more clearly here.

I don't really think using Maybe mixed in with the logic of your application is a good idea.  As an example I think the problem presented in that article could be solved much more clearly with this bit of code.  Here's a solution that will never return nil.



My suggestion is that if you find yourself wrestling with possible nil return values .  See if you can turn the operation on it's head.  Don't ask your object about it's associations.  Ask the association about your object.  I often find this will clean up the logic.

I did however just release JustMaybe so obviously I think it's useful in some way?  For me that's almost strictly in presentation.  When you are presenting information you often have to reach deep down into the hierarchy of objects to extract the necessary bits.  Interestingly, at presentation, is when I think you should be deciding what to display when information is missing.  To me that creates a perfect situation for using the Maybe pattern.