The Art of the Shortcut

by Charles Miller on April 4, 2004

One thing you see a lot in Java programmers is the use of Javabean-style properties: classes with a pile of "get" and "set" methods that allow you to manipulate their state. Now the arguments as to whether this is acceptable practice or Considered Harmful are legion, and I'm not going into them today. Suffice to say I spend most of my time writing Java, and some habits get carried around with you.

One thing I wanted to do in Ruby, though, was to find some way to lessen the pain caused by having to change a bunch of properties at once. I did so by adding a method to the Object class that would allow me to pass in a hash of name->value pairs, and have them automatically mapped to object property "setter" methods. (In Ruby, the convention for a setter is to have a method called "foo=", which through a little operator-overloading magic allows you to write "myobject.foo = bar" in your code)

class Object
  def set_properties(props)
    props.each { |key, value| self.send("#{key}=", value) }
  end
end

This makes the following fragments of code equivalent:

  1. user.name = "Charles"
    user.email="cmiller@pastiche.org"
    user.website="http://fishbowl.pastiche.org"
  2. user.set_properties ({ :name => "Charles", 
      :email => "cmiller@pastiche.org", 
      :website => "http://fishbowl.pastiche.org" })

Of course, one of the most important things one should make sure of when writing a shorter way to do something, is that the short way isn't, say, 30% longer than the one you started with.

"Alright, we're here. Let us never speak of the shortcut again.".

Previously: Penny Arcade's Greater Internet Fuckwad Theory

Next: Cut With the Grain