Whenever I write functions in dynamically-typed languages, I’m still torn as to what is the best thing to return to make it easy to both handle errors in calling function and keep program flow fluid.
What does the community think are the right things to return when things don’t go right in functions using dynamically-typed language?
My general thoughts are:
-
if you are returning an actual value, you should either return data using that type if the function successfully executed, or null if something was unexpected.
-
throwing exceptions should be reserved for generic utility functions
-
you should not return a default value for a particular type if errors occurred, e.g., if the user expects a string, you should not return the empty string if errors occurred.
When an exception occurs (in the meaning of the word) throw an exception.
nullis something like “nothing”, that does not inevitable mean, that an error occurs. For example afind()-method may returnnullin case it found nothing, that matches some given criteria. When you definenullas “error”, then you have a kind of magic value, like the good old “magic numbers”, that always must be documented and such.