Module-level variables
1 25 Jan 2017 17:30 by u/jxfaith
Quick question regarding best practices in code:
I have several module-level variables that are declared and used in various locations throughout a script. They function as parameters which control various aspects of specific behaviors (timing, references, etc).
Is it considered sloppy to leave these variables sitting in the module scope like that or should they be encapsulated?
I don't anticipate a need for run-time modification of these variables, just curious whether it's considered a best practice to shove these variables into a struct or object instead of just plopping them in the module and calling it done.
3 comments
1 u/RevanProdigalKnight 26 Jan 2017 18:55
Since they're module level, they're essentially global variables inside that module. The "Best Practice" part of me would say to put them in a
module_globalsorconfigobject so that you only have one "global variable" for the module. The pragmatic part of me says that unless it becomes a problem, they're fine where they are - less worry about needing to refactor all the code that depends on them that way.0 u/J_Darnley 26 Jan 2017 01:14
In general variables should be as locally scoped as possible. You don't even say what language you're using so I doubt people can be specific.
0 u/jxfaith [OP] 26 Jan 2017 01:31
In this case, it's Javascript. I've ended up doing this in a couple of other languages though (C#, C++).
Thinking about it at greater length, there would be a reasonable improvement in readability if I nested these variables within a struct or object simply because every reference to such a variable would hold the name of the corresponding struct or class. Rather than having to remember that these variables are held at the top of the script, they would know to look for the corresponding struct or class declaration to find them instead.