Least Significant Bit

Ask Hack Learn Share!

Antipatterns: Exceptions for flow control

In a recent pull request of mine at work a colleague called my attention into an antipattern I had in the code, namely Using exceptions for flow control, and he was right. So we just had to change it.

A simplified version of the code is this

def a_method
  a_hash['key_to_an_array'].first
rescue
  {}
end

this code hides different problems that can happen accessing the hash and the array in the value of the hash, e.g. the hash is nil, the value of key_to_an_array can be nil or not respond to first, and maybe even more, you name it. More important is that the code is not clearly showing the problem, rather it is hiding things by saying whatever the problem it is, just return an empty hash.

After a while we analyzed the cases and things were not that easy, edge cases appeared, so it was not just a matter of style anymore, so we came up with this other version

def a_method
  a_hash['key_to_an_array'].try(:first) || {}
end

Performance

We’ve ran some benchmarks and the results are almost the same in both implementations for amounts below 1000, they start to differ above 100 000 which we will never reach in a request anyways. But still it was worth fixing.

Kudos to Raúl Galindo for making me improve what I deliver.

blog comments powered by Disqus