ActiveRecord callback names should be expressive

ActiveRecord provides a bunch of useful callbacks which will be run at various stages during the lifecycle of an ActiveRecord object. There are lots of ways to define these callbacks, and the easiest way is something like this.

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

Seems harmless enough, right? Sure, as long as you're writing a throwaway prototype. Try adding another after_save callback, or implementing the callback in a subclass. Try coming back to the callback after 6 months and trying to work out what it's meant to be doing. That way insanity lies.

Name your callbacks expressively and you'll reap the immediate benefits of more readable code and easier implementation. You'll also have a decent indication - the method name - of what the callback was meant to do when you come back to the code in 6 months.

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

Related articles

Leave feedback...

  1. From my experience, I can just say: you’re absolutely right.

Commenting is closed for this article.

About the boy

A picture of Craig in grayscale

Craig Webster is a software engineer living in London. He usually works with Ruby although sometimes he sneaks in some Erlang or JavaScript. He's into rock climbing, snowboarding, skating, photography and fencing. Yes, this does mean he has a sword.

Near here you'll find Craig's homepage, contact details, PGP key and keysigning policy, and talks.

Licence

The entire content of this blog is public domain. Use it however you fancy. You don't even need to attribute it to me, although it would be nice if you did. Just don't sue me and we'll all be happy.

I Work With Rails

Recommend Me

My Travels

I go places. Do you go places too? Let's meet up!.