JT Hopple LLC

Pass the Hash

JeremyProgramming, Rails, Ruby Digg!

Code readability is an undisputed contributor to increased programmer productivity. Ruby on Rails shines in this department by effectively using two main pieces of Ruby — the hash and the symbol. These two things are used all throughout Rails, but most importantly as method parameters. There are two keys to keep in mind when writing methods:

  1. When passing multiple data parameters to a method, pass a hash
  2. When telling a method how to behave, pass a symbol

From a code readability standpoint, this is huge. Using the ActiveRecord::Base.find method as an example, what's more readable?

  1. Article.find(:all, nil, :tags, "tags.name = 'ruby'", "articles.created_at DESC")

or the way it's done in ActiveRecord...

  1. Article.find(:all,
  2. :include => :tags,
  3. :conditions => "tags.name = 'ruby'",
  4. :order => "articles.created_at DESC")

The second example is more readable. When reading the second example it's very quick and easy to comprehend exactly what is being passed to the method. Sure, the first method works and requires less typing, but the only way to know for sure what's being passed is to either have the method's prototype memorized or look it up in the reference. The other thing to note about the find method used above is that it takes a symbol as it's first parameter. This symbol clearly and immediately specifies the desired behavior of the method.

Keep this in mind when writing new methods that accept more than one obvious parameter. In addition to writing code, programmers need to be able to read code. This simple habit of passing parameters as a hash or a symbol will increase code readability and improve programmer productivity.

2 Comments

<<the only know way to what for sure>> or, just get a better IDE!

Yes, you can always choose to rely on an IDE to show you what's going on in your code. I'd rather just have readable code.

Post a comment