Reputation: 1208
In my program, the user supplies an array that defines which functions are run in a loop. I have a bunch of variables which must be passed into each of the functions. The list seems to consistently grow and is becoming difficult to maintain since the argument list appears in many places. Here is some pseudo code:
var fn_defs = {
test_fn_1: function(test_var_1, test_var_2, test_var_3, test_var_4, test_var_5, cb){
//...do stuff
},
test_fn_2: function(test_var_1, test_var_2, test_var_3, test_var_4, test_var_5, cb){
//...do stuff
},
etc...
};
async.eachSeries(user_defined_list_of_function_names, function(fn, async_cb){
var test_var_1, test_var_2, test_var_3, test_var_4, test_var_5;
fn_defs[user_defined_list_of_function_names](test_var_1, test_var_2, test_var_3, test_var_4, test_var_5, function(result){
async_cb();
}, function(err){
//end
});
});
Looking for a better way to do this. I guess I could just make global variables but I imagine that is also an anti-pattern.
Upvotes: 2
Views: 956
Reputation: 393
This pattern (many arguments to a function) is pretty common in javascript. Many functions in popular javascript libraries take a LOT of parameters. They enclose these arguments in an object which collects all parameters in one argument and simplifies giving optional parameters.
For example, JQuery UI animate function, it takes 11 arguments. All the arguments are encapsulated inside an object. Passing object with missing parameters will use this parameters default value.
function dostuff(args){
var def_args = {step: 1, state: 'PENDING', vas: function(){}};
args = merge_options(def_args, args);
}
Upvotes: 2
Reputation: 749
If you are using an internal interface, you can use a DTO (http://en.wikipedia.org/wiki/Data_transfer_object) in summary you can create a simple object to group all the variables.
Upvotes: 1