ActiveRecord Callback Names Should Be Expressive

December 01, 2008 · 1 min read

ActiveRecord gives you a bunch of useful callbacks that fire at various points during an object's lifecycle. The quickest way to define one looks like this:

class Widget < ActiveRecord::Base
  def after_save
    # What did this code do again?
  end
end

Seems harmless enough, right? Sure, if you're building a throwaway prototype. But try adding a second after_save callback. Try overriding it in a subclass. Try coming back to this code in six months and remembering what it was supposed to do. That way lies madness.

Give your callbacks expressive names and you'll immediately get more readable code that's easier to extend. You'll also leave yourself a helpful clue — the method name itself — about what the callback was meant to do when future-you comes back to this code.

class Widget < ActiveRecord::Base
  after_save :add_widget_to_bill_of_materials

  def add_widget_to_bill_of_materials
    # No need to guess what this method does,
    # it's right there in the name!
  end
end

It's a small change that pays dividends every time someone reads the code — including you.

Questions or thoughts? Get in touch.