Sunday, 14 December 2014

12 Tips of Christmas - 4 Null Objects

4. Null Object pattern

Sometimes you may find yourself co-opting nil, where we test to see if an object is nil and change the methods behaviour accordingly. Issues can arise right down to the view layer as we constantly check to see if a particular object is nil or not, i.e.: 
- if @membership.present?
  = @membership.plan
- else
  "Guest"
Enter the Null Object pattern.
A good use case for Null Objects are guest memberships, where we need them to conform to the regular membership API, but respond slightly differently.
class GuestMembership
  def active?
    false
  end

  def paid?
    false
  end

  def plan
    "Guest"
  end
end
Now, when we determine what membership is displayed, we make that decision not in the view, but in our model, or other class. This means our view can now look like this instead:
= @membership.plan
The downside to this pattern, is that you now need to maintain two sets of API's, but used sparingly, I really like how this enables me to pull logic out of views and even models, where I query to see if an object exists or not.

No comments:

Post a Comment