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: 2024-03-02

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

_, _, score =

if score < 0.5

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

if (! score) || score < 0.5


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.