How do you handle improper function arguments?

twitter logo github logo ・1 min read

I've recently been thinking about how to improve my code patterns to give my work a more consistent and easy to understand feel.

Working functionally means that every function must return a response. If a function was to receive incorrect arguments, then how should it respond?

Returning false for any anomalous behaviour (invalid input/error catch) and handling that in the parent is the best solution I have come up with.

How do you handle this scenario?

twitter logo DISCUSS (3)
markdown guide
 

I find that Either and Maybe (also known as Optional) are good ways of handling functions that can return a successful result or a failure. I tend to avoid throwing errors in Javascript because then both programmatic and application errors fall in the same bag and if I want to handle some errors in different places than others I need to catch and rethrow, polluting the error stack.

A while ago I wrote an article about handling errors with Either and Maybe, you might find it interesting.

 

My approach FWIW:

It if was an error in the system itself, I throw an exception. I very rarely find myself in this situation. An example might be getting a connection to a Database. If the database service won't connect I throw an exception.

If it is an expected situation I use guard clauses at the top of the function that will return an object that represents a lack of a result. For example, if I am supposed to fetch a list of something, and get bad input, I return an empty list if the calling code knows an empty list is a bad result. For example, if I am requesting a list of cities for a given country code, I return an empty list if the input is bad. This gives the calling code the opportunity to decide if it thinks the result is bad or not. In this case, it definitely is: all countries have cities, so the input must be bad.

As a general rule, you want to make sure your code doesn't have to guard against itself. If you're building libraries for use by 3rd parties, where you expect that people will misuse your API, then you expect devs to not fully understand our library and need to guard against misuse. However, if it's your code calling your code, then guarantee your calling code cannot and will not ever pass bad arguments to the code it is calling.

 

There should be a validate function to validate your initial input and if the input is invalid, the system should throw a meaningful error for end-user, like BadRequestError. That's my idea

Classic DEV Post from Dec 22 '18

The 10 most popular dev.to posts of 2018

I took the 10 most popular posts in the year section of dev.to and added some t...

George profile image