A lot of frameworks, most like jQuery plugins uses the \"optional\" parameter. B
ID: 648512 • Letter: A
Question
A lot of frameworks, most like jQuery plugins uses the "optional" parameter. Basically a dictionary (or key/value structure) with a bunch of additional parameters instead of send in the parameter's function.
As an example:
function (param1, param2, param3, param4, param4) {
...
}
Is replaced for:
function (opts) {
opts.param1
opts.param2,
opts.param3
...
}
IMO using opt is almost equal to use a lot of parameters in the constructor. I think is a little hard to maintain the configurations (sometimes) and understand what is inside of it.
Maybe it is for non typecheck of javascript, and the IDES normally doesn't help easily to know what is inside of opt.
But I don't know how to improve the creation of a configurable object.
Someone knows better solution or how to improve the design in this situations?
Explanation / Answer
I would say it depends of the language. In a strongly typed language like Java, pasing a Map<String, Object> means that you risk using the wrong type for a parameter.
That said, I have seen this been used in frameworks like ExtJS and, for some tasks that require lots of parameters (like initialization, configuration) it is worth it. It actually helps, because when building the objects you have the param name right next to the value, instead of having to count which parameter it is in the function argument list and count which parameter you are actually using.
Compare this code
function createWindow({
top: 10,
right: 10,
width: 100,
height: 200,
title: 'My title',
text: 'My text',
buttons: [button1, button2],
borderStyle: myBorderStyle
});
to
function createWindow(
10,
10,
100,
200,
`My title`, /* I am sure it is the right order? or is text before title? */
`My text`,
null, /* I do not need this param, or the next other 3*/
null,
null,
null,
[button1, button2],
null,
null,
null,
myBorderStyle /* This is the 13th or the 12th parameter? */
);
Which one is easier to understand?
Additionally, you can use the builder pattern to set parameters in the dictionary, something like
var conf = {}
setTop(conf, 10);
setRight(conf, 10);
...
although IMO you are not improving the first version (and I don't actually see it being used much).
Now, for strongly typed languages, I would use a ConfigurationClass, where each parameter is defined as an attribute and its type is defined, but in JS there is little use for that since, if you write the attribute name wrong, the compiler won't tell you.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.