Watch out for API functions with multiple return types

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the functions category.

Last Updated: 2021-05-16

I was caught off guard working with a third-party API that normally returned a number, but sometimes returned nil.

_, _, score = FuzzyMatch.new(possibilities).find_with_score(name)

if score < 0.5
  do_something
end

Since nil < 0.5 doesn't work, this blew up and I had to rewrite the code as:

if (! score) || score < 0.5
  do_something
end

Lessons:

Consult the docs whenever using a library function and enumerate the possible return types, then ensure your code can handle these. Be especially careful about possible nil and possible exceptions.

Be especially careful about assuming numerical functions always return numbers. Just because you might expect 0 in error conditions doesn't mean they will provide that.