Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is it bad practice to parameters through a string of functions?

im building a reasonably large JS application and i wanted to get your opinions on some of the logic. i wanted to know if its considered bad practice to pass a parameter through a string of functions e.g.

function start(){
    var param1 = 'me';
    secondFunction(param1);
}

function secondFunction(param1){
    //i dont want to user the param in this function
    $.ajax('url',data,success(){
        third(param1);
    });
}

function third(param1){
    alert(param1);
}

i guess the alternative is to use global varialbes , as below. But in my case i already have a mass of global variables and, in my eyes, some things are not important enough to the global workings of the application.

var param1;

function start(){
    param1 = 'me';
    secondFunction();
}

function secondFunction(){
    //i dont want to user the param in this function
    $.ajax('url',data,success(){
        third();
    });
}

function third(){
    alert(param1);
}

So would you say passing parameters through more then one function is ok or should i be doing it another way?

Thanks

like image 317
nathajamal Avatar asked Feb 25 '23 00:02

nathajamal


1 Answers

Actually, that's good practice because it avoids having any global state (i.e. ideally, the behaviour of a function would only depend on its parameters).

If you have many parameters to be passed through this way, I'd batch them together in a separate object (an 'environment' object) but apart from that it's totally fine.

Doing it this way gives you a lot of flexibility - if you want a function to operate on different data once, you'd just pass in different values, rather than changing the global state, which might affect everything else, too (Having no such global side-effects makes it very easy to parallelize functions, even though that may not be so important for JavaScript).

like image 188
Alexander Gessler Avatar answered Mar 23 '23 00:03

Alexander Gessler