Null Objects in Ruby

I just did an exercise running through null objects in ruby. We don’t really use them at any company I’ve worked for, so it was interesting to try out a new technique. If you are unfamiliar with null objects here’s the idea:

Null objects are beneficial when you would otherwise be checking if an object is nil or empty throughout your code.

The example in the assignment was subscriptions. You have a user and a user is attached to a subscription. However, a subscription can be a free trial or no plan, in addition to regular, paid subscription. For a free trial, price and charge are both 0 and nil, respectively. Instead of checking if subscription.nil? I can create a NullSubscription and do something like this within the user class:

def subscription
  if free_trial?
    FreeTrial.new
  else
    @subsciption || NullSubscription.new
  end
end

So now, instead of checking if @subscription is nil and then setting price, we can call @subscription.price and always get a real value (assuming we are seeing price to zero in our NullSubscription class.