mardi 20 octobre 2015

How can I avoid passing null parameters to a function with multiple optional parameters?

I have a function that looks something like this:

function f(requiredParamA, requiredParamB, optionalObjectParamA, optionalObjectParamB) {
    optionalObjectParamA = optionalObjectParamA || {};
    optionalObjectParamB = optionalObjectParamB || {};

    // rest of the function
}

Say I want to call f with a value for the optionalObjectParamB, but not for optionalObjectParamA. I could do this:

f("john", 100, null, {vegatarian: true});

But that makes for an ugly API. Is there any other option? How should I design the function and how should I call it?




Aucun commentaire:

Enregistrer un commentaire