views:

402

answers:

4

What's the best way to pass an optional argument that is nearly always the same? Case in point is Javascript's parseInt function; the second argument for radix is optional, but to avoid a string beginning with a zero being treated as octal, it is generally recognized good practice to always specify 10 as the second argument. Fair enough, so I'm wondering, how to best deal with this situation; specifically, should I create a convenience function, such as parseBaseTenInt(str), that just returns parseInt(str, 10)? I've inherited one file of code with about 10 calls to parseInt without the second argument, and creating the convenience function will subsequently allow me to do a simple replacement of parseInt with parseBaseTenInt. However I can conceive of drawbacks to the convenience function, particularly it not being used by other developers. Because it's just 1 file right now, and I will the primary developer moving forward, it wouldn't be too inconvenient to just add the second argument to all the parseInt function calls.

+1  A: 

I'd go with your solution - wrap it in a suitably-named function, keep it's behaviour/calling convention consistent with the library function, and use the wrapper function.

gkrogers
A: 

Depending on the number of parameters you might want to Introduce Parameter Object along with your convenience function. Then you can set defaults for your parameter object and only set the properties that vary when you use the function.

Jason Punyon
+1  A: 

We use a lot a functions that apply a default if the passed value is null.

// base defaults to 10
function ParseInteger(str,base)
{
    if(base==null)
        base=10;
    return parseInt(str,base);
}
chills42
check `arguments.length < 2`, `typeof base === 'undefined'` or `typeof base !== 'number'` - `base == null` is the wrong test, but works (for some value of 'works') because of implicit type conversion
Christoph
Good to know, I didn't realize that before...
chills42
it's a bit confusing that there's `undefined` and `null` in javascript - one means `I don't exist` (no value has been set), the other something along the lines of `I exist, but don't` ;) (a value has been set, but it's 'nothing')
Christoph
You also might want to explicitly pass 'null' to mean 'give me the default', however, especially if (a) a wrapper function which also has default arguments is calling it, or (b) you add extra arguments afterwards. The above is the common JavaScript idiom for default arguments.
bobince
A: 

You can either check how many arguments have been passed using arguments.length inside the function.
Or you set default values for each variable by using the || operator:

function foo(bar, baz) {
    bar = bar || "default";
    baz = baz || 0;
    return bar + ", " + baz;
}
foo();                 // "default, 0"
foo("some string");    // "some string, 0"
foo("some string", 1); // "some string, 1"
Gumbo