Documenting your parameters
April 11th, 2008
Consider you are reading a chunk of code, and you see a method
mock_person('jack', 1, 24, 72, 180)
You’ll probably wonder what the parameters are. As you know, you should avoid using magic constants in your code; they make it less readable, and if you have just numbers in the code, you can’t easily change all instances of, say, 4, to something else (how do you make difference between values of 4 you want to replace, and coincidental values of 4?). If the original developer had been smarter, he would’ve probably written something like
name = 'jack' uid = 1 age = 24 weight = 72 height=180 mock_person(name, uid, age, weight, height)
but it’s not too pretty either; first, it bloats the code, second, it pollutes the namespace and allows modification of parameters later on. This wouldn’t be a problem with immutables, but what if any of the parameters was a mutable object with some state?
Luckily, an assignment statement in Ruby has a return value, which is the evaluated value of the right-side expression. So,
a statement name = 'jack' would return value "jack".
Now, a simple call
mock_person(name='jack', uid=1, age=24, weight=72, height=180)
would return exactly the same object, while not polluting the caller’s scope.
Ok, it’s not THAT useful, but especially when writing unit specs/tests (which should be very readable!) it allows for easy documentation of your parameters without any additional setup and/or hacks at all.

Leave a Reply