I was creating a helper on a Rails app. That helper returned a path, and it had to have params in a fancy arrangement. It looked something like this:
def path_to_conditions(model, condition_to_exclude)
params = {q: {}}
model.conditions.each do |name, value|
next if name == condition_to_exclude
params[:q][name] = value
end
some_path(params)
end
This got the tests passing, but I knew I would come back to it because, to put
it simply, each
might be a code smell. So, I used good old reduce
:
def path_to_conditions(model, condition_to_exclude)
params = model.conditions.reduce({q: {}}) do |params, (name, value)|
next params if name == condition_to_exclude
params[:q][name] = value
params
end
some_path(params)
end
Working great, but Rubocop wisely suggested each_with_object
to shave off a few
lines:
def path_to_conditions(model, condition_to_exclude)
params = model.conditions.each_with_object({q: {}}) do |(name, value), params|
next if name == condition_to_exclude
params[:q][name] = value
end
some_path(params)
end
Green specs again. I was ready to ask some of my thoughtbot friends if they
thought the reduce
or each_with_object
versions were actually more readable
than the each
one when I noticed that “fancy param arranging” I was doing
was not fancy at all. In fact, it could be done in one line of code:
def path_to_conditions(model, condition_to_exclude)
some_path(q: model.conditions.except(condition_to_exclude))
end
🤦🏽♂️
So, what’s the deal?
First, this was my daily reminder to Keep It Simple, Stupid. We tend to reach for complexity very eagerly. It’s good to take a step back and think about what we’re doing. If something feels hard to implement, there’s a good chance that we can look at the problem from a different perspective and find a much more straightforward solution.
Secondly, we must keep in mind that not every code we write needs to go to production. Sometimes we need to feel the implementation to understand if it’s the right answer and what are the next steps. We can use code to put our thoughts “on paper” and then organize them. Seeing the big picture helps us to throw away what’s unnecessary.
Although we might forget it, code is not a solution to everything, so let’s not get too attached to it.