Is it better to "overload" the function or have two separate functions when dealing with multiple types of arguments

I am writing a function that takes an array of word objects and then modifies the word objects. I would like the user to be able to use the function on a separate word object as well, and I'm wondering which one is better:

a) have a function type, check if the input argument is an object or an array and correspond accordingly b) have two functions: one for obj and the other for an array.

//method 1: accepts either a obj or an array
function wordChecker(element) {
    if (typeof element === 'object') {
        wordCheckerHelperHelper([element]);
    } else if(element instanceof Array) {
        wordCheckerHelper(element);
    } else throw new Error('invalid argument');
};

function wordCheckerHelper(arr) {
    //do something
};

//method 2: separate methods, but the wordCheckerObj method is just a wrapper around the wordCheckerArr method
function wordCheckerArr(arr) {
    //do something
};    

function wordCheckerObj(obj) {
    if(typeof obj !== 'object') throw new Error('invalid argument');
    workCheckerArr([obj]);
}

      

+3


source to share


1 answer


JavaScript libraries usually take the first approach, i.e. take any argument and try to deal with it somehow. I guess this is mainly due to the dynamic nature of JavaScript, users are often unaware (or unsure) about the type of object they got from another system / library. Detection types in JavaScript can be quite tedious, and user code will eventually be a huge amount if

, and switch

es, so these types of tests is better encapsulated at the level of the library.



0


source







All Articles