tags:

views:

82

answers:

3

I am working in a group that is writing some APIs for tools that we are using in Ruby. When writing API methods, many of my team mates use hash tables as the method's only parameter while I write my methods with each value specified.

For example, a class Apple defined as:

class Apple
  @commonName
  @volume
  @color
end

I would instantiate the class with method:

Apple.new( commonName, volume, color )

My team mates would write it so the method looked like:

Apple.new( {"commonName"=>commonName, "volume"=>volume, "color"=>color )

I don't like using a hash table as the input. To me is seems unnecessarily bulky and doesn't add any clarity to the code. While it doesn't appear to be a big deal in this example, some of our methods have greater than 10 parameters and there will often be hash tables nested in inside other hash tables. I also noticed that using hash tables in this way is extremely uncommon in public APIs(net/telnet is the only exception that I can think of right now).

Question: What arguments could I make to my team members to not use hash tables as input parameters. The bulkiness of the code isn't a sufficient justification(they are not afraid of writing 200-400 character lines) and excessive memory/processing overhead won't work because it won't become an issue with the way our tools will be used.

+3  A: 

First of all, you should chide them for using strings instead of symbols for hash keys.

One issue with using a hash is that you then have to check that all the appropriate keys are in it. This makes it useful for optional parameters, but for mandatory one, why not use the built-in functionality of the language? For example, with their method, what happens if I do this:

Apple.new( {"commonName"=>commonName, "volume"=>volume} )

Whereas, with Apple.new(commonName, volume), you know you'll get an ArgumentError.

Pesto
A: 

Named parameters make for more self-documenting code which is nice. But other than that there's not a lot of difference. The Hash allows for more flexibility, especially if you start doing any method aliasing. Also, the various Hash methods in ActiveSupport make setting defaults and verifying inputs pretty painless. I guess this probably wasn't the answer you were looking for.

Mike
+4  A: 

Actually if your method takes more than 10 arguments, you should either redesign your class or eat dirt and use hashes. For any method that takes more than 4 arguments, using typical arguments can be counter-intuitive while calling the method, because you got to remember the order correctly.

I think best solution would be to simply redesign such methods and use something like builder or fluent patterns.

Hemant Kumar