Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
6
rated 0 times [  7] [ 1]  / answers: 1 / hits: 68755  / 14 Years ago, wed, november 10, 2010, 12:00:00

I know that global variables are bad.



But if I am using node's module util in 40 files in my framework, isn't it better to just declare it as a global variable like:



util = require('util');


in the index.js file instead of writing that line in 40 files?



Cause I often use the same 5-10 modules in each file, that would save a lot of time instead of copy paste all the time.



Isn't DRY good in this case?


More From » module

 Answers
23

Each module is supposed to be independent. The require doesn't cost anything anyways after the first one for each module.



What if you wanted to test one module alone? You'd be having a lot of issues because it wouldn't recognize some global requires that you have in your app.



Yes, globals are bad, even in this case. Globals almost always ruin: testability, encapsulation and ease of maintenance.



Updated answer Jan. 2012



The global object is now a global inside each module. So every time you assign to a global variable (no scope) inside a module, that becomes part of the global object of that module.



The global object is therefore still not global, and cannot be used as such.



Updated Dec. 2012



The global object now has the global scope within the application and can be used to store any data/functions that need to be accessed from all modules.


[#95028] Saturday, November 6, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
marisela

Total Points: 103
Total Questions: 105
Total Answers: 102

Location: Solomon Islands
Member since Fri, Oct 8, 2021
3 Years ago
;