I'm a Floridian web engineer who planted his roots in Paris. Some of my favorite past-times are analyzing and optimizing development processes, building solid APIs, mentoring junior devs, and long walks on the beach.

Definition vs Function/Methods Style

I was recently reading The Rails 3 way by Obie Fernandez when I came across a section of the book that was talking about how Ruby allows for a definition-style as opposed to a funtion-style. That is to say, using a function call without including the open and closing parentheses. Typically, I like using functions without parentheses because I feel that the function looks more clear.

I much prefer to see:

link_to "Some page", some_page_path

instead of:

link_to( "Some page", some_page_path )

Especially in a haml template, the first style looks nicer. However, "The Rails 3 way" mentions that one of the key benefits parenthesis-less function calls offer is macro-like feeling and should be a signifier that this call will affect other things and not act directly. Indeed when you look at the following code:

class Client < ActiveRecord::Base 
  has_many :billing_codes
  has_many :billable_weeks
  has_many :timesheets, :through => :billable_weeks

class Client < ActiveRecord::Base
  has_many(:timesheets, :through => :billable_weeks)

You can see that the first one looks cleaner. It also looks more like a declaration. Indeed, the has_many function alters the object of the class that calls it giving all of it's instantiated objects a slew of other functions. This theme happens over and over again in the Rails framework. The filters that are added to controllers, such as before_filter and after_filter, will alter the functionality of actions that get called.


The problem with the definition-style method is when there are nested functions which take parameters. For instance, if the function for generating the page for some_page requires parameters as well:

some_page_path( :user_id => current_user.id, :name => 'derp' ) # calls the path for some page

This will cause problems when the following call is made:

link_to "Some page", some_page_path :user_id => current_user.id, :name => 'derp'

In the link_to call, it can't be determined whether the :name parameter should be part of the params for link_to or part of the params for some_page_path.

Since consistency is always preferred, it is better to always use parentheses with function calls only leave them off only when the function is being used to alter the class in some way.