The blog of Rahoul Baruah from 3hv Ltd

What's going on?

My name is Rahoul Baruah (aka Baz) and I'm a software developer in Leeds (England).

This is a log of things I've discovered while writing software in Ruby on Rails. In other words, geek stuff.

However, I've decided to put this blog on ice - I would ask you to check out my business blog here (or subscribe here).

30 January, 2008

Why hashes as named parameters in Ruby are a good thing

Back when I used to do lots of Sql Server Transact-SQL, I used to dislike named parameters. They annoyed me and I only used them when I had a stored procedure with a large number of parameters, some of which were optional. (As an aside, we had procs with parameter lists running into twenty or thiry, some of which were optional and some were mandatory - it was a nightmare and named parameters were essential in those cases).

Odd though. Named parameters turn out to be one of my favourite Ruby features - even though Ruby doesn't have them. And, even odder, they used to be one of my favourite Smalltalk features (Smalltalk has always had them).

Today, my learned colleague was on a roll. Fantastic design ideas were flowing. One issue he was busy solving was handling an image at multiple sizes. The application had an ActiveRecord class representing a file - and if the file were an image then it could store that image at multiple resolutions. He proposed something along the lines of this: my_file.required_size(width, height) - the implementation would then hunt through the related images at various sizes, pick out the correct one and return it. This meant that a view would have code looking something like this:

image_tag my_image.required_size(400, 300).web_url, :alt => h(my_image.description).

His proposed implementation was fine - but I suggested renaming the method at - so you could write my_file.at 400, :by => 300.

"But at doesn't explain the method's purpose" was the reply. "That's why you should name the second parameter and pass it as a hash" said I. This would make your view code look like this:

image_tag my_image.at(400, :by => 300).web_url, :alt => h(my_image.description)

Personally, I think this is much easier to read and, with the named parameters, explains the intention of the at method perfectly (although the brackets spoil it a bit).

The key difference between the two languages is that in Ruby, the method is named "at" and you call it as my_file.at 400, :by => 400. In Smalltalk, methods names include the parameters - so it is named "at: aWidth by: aHeight" (and you would call the method by writing myFile at: 400 by: 300.).

The Smalltalk idiom of including the parameter names within the method name is much clearer at explaining the method's intention. And the very act of naming your parameters means you can apply much more meaningful sentences within your code - which is exactly what Alan Kay meant for us to do all those years ago. Don't you agree?

No comments:

eXTReMe Tracker