Let’s say you have to write a function that doubles a given number. You also find out that you may get one number (in which case double that number), or multiple numbers (double all numbers).
The first thought that comes to mind is to -
- use different functions (or)
- check type of input and process differently
Consider the below code -
|
|
The given option is workable, but there is a shortcut way to do the same.
|
|
The added advantage is the consistent output signature - the function output is always an array.
So, why would you want to do this?
- Use same function without changes for one or more than one arguments
- Lower the number of function calls - it’s a better option as compared to calling function in a loop or having branched out logic for different types
Of course, you cannot have this kind of logic in all places. But, have this option in the back of your mind while designing your functions.