Remove Argument-Order Dependencies
September 17, 2013
I’m now working my way through the third chapter of Practical Object-Oriented Design in Ruby where we are learning about managing dependendies between objects.
Distracted by a shiny new operator
The first thing that I want to mention is the use of the ||= operator. I had never seen the “or equals” operator before and so I was distracted for awhile from this chapter until I read enough about it’s meaning to figure out what it does.
Using a hash as a paremeter
This chapter talk about several different ways to reduce your dependency on other objects, but the one about using a hash to pass in parameters really tickled my fancy. Here is an example class that I made up that passes in a hash of arguments.
class Foo
attr_reader :apple, :orange, :taco, :juice
def initialize(args)
@apple = args[:apple]
@orange = args[:orange]
@taco = args[:taco]
@juice = args[:juice]
end
...
end
Foo.new(
:apple => 3,
:orange => 7,
:taco => Taco.new(14, 2),
:juice => 19).food_calculate
The benefits of using a hash are:
- It removes every dependency on argument order
- Adds verbosity
- The
keynames in the hash tell us what we are passing in.
I really like point #3 because without the hash our code will be confusing and we won’t know what the numbers mean when we create a new Foo object like this:
Foo.new(3, 7, Taco.new(14, 2), 19).food_calculate
This section of the chapter really stood out to me because I really could have used this today at work to make it much more clear about what I was passing into one of my classes.