Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Null Object Pattern

Gordon Diggs
September 28, 2012
49

Null Object Pattern

Presented to @paperlessdev on 9/28/12

Gordon Diggs

September 28, 2012
Tweet

Transcript

  1. And I learned about this thing called the Null Object

    Pattern. Friday, September 28, 12
  2. Right now we do things like this: if @guest &&

    @guest.attending? do_attending_stuff end Friday, September 28, 12
  3. The Null Object Pattern seeks to remove the excess logic.

    @guest = Guest.find_by_id(params[:id]) || NullGuest.new ... class NullGuest def attending? false end end Friday, September 28, 12
  4. But this can get a bit tedious: class NullGuest def

    act!(action) end def additional_guests nil end def attending? false end def blank_name? true end def display_name_or_email nil end def email_address nil end def email_address_id nil end def member? false end def not_attending? false end ... Friday, September 28, 12
  5. How it’s used class NulllGuest include Nobody returns_false_for :attending?, :not_attending?

    returns_true_for :blank_name? returns_nil_for :display_name, :personal_note def state 'initialized' end end Friday, September 28, 12
  6. How it works • Define methods on the given class

    that return a specific value using Ruby’s define_method • Could in theory allow any return value Friday, September 28, 12
  7. Final thoughts • The wiki page on Null Object Pattern

    sucks. Don’t read it. • Null classes can get tricky because of coupling • Metaprogramming is hard. Friday, September 28, 12