I have a very simple question that has been haunting me for a while when my code starts growing.
Should parameters be replaced by global variables when they go through long routes of nested function calls?
I understand that global environment can make the state of a program unpredictable because many functions can modify shared variables, but still, global space makes things so easy.
Let me explain myself:
functionA(){
x = something
functionB(x)
}
functionB(x){
functionC(x)
}
functionC(x){
finallyDoSomethingWithX(x)
}
finallyDoSomethingWithX(x){
x += 1 //Very dummy example ignoring pass by value, not reference.
}
Replaced by:
globalX;
functionA(){
globalX = something
functionB()
}
...
...
...
finallyDoSomethingWithX(){
globalX += 1
}
I feel the second way gives so much freedom to program because parameters can accumulate easily and also can be very restricting sometimes when code must be reused, but at the same time I feel like the function will loose its modularity when it is related to a variable in the global environment, also loosing reusability when, for example, I want to operate finallyDoSomethingWithX
with another variable different tha globalX
.
I think this is happening to me because I'm not actually using design patterns because I'm programming in Javascript, which for me feels like a one-script-deals-with-all language for medium projects.
Any advices? patterns? I can be more specific if needed.