Ruby Stuff

A Good Case for NullObject in Ruby

Ben Orenstein of thoughbot gave a talk about Refactoring in which he mentions using the NullObject pattern (or ‘Replace conditional with polymorphism’). I liked the idea, and it didn’t take long to come across a situation where it made sense.

With Conditionals

This type of thing is pretty common, but it’s not DRY and it’s distracting:

With NullObject

If we have a NullReport, watch how easy this becomes:

This is nothing more than a cool OOP tool. I could get deeper in and make individual methods for any special messaging I want to present, like “No dates available.” There will be cases where method_missing causes issues, but it works in this particular scenario.