DEV Community

Discussion on: Why are global variables bad?

Collapse
 
fnh profile image
Fabian Holzer • Edited

"It helps your code to easily pass and access data from other classes and methods."

If you need to pass data to a function or a class method, those data clearly should be parameters. In case you have an object, the data might be instance variables. But global variable is not appropriate as a means of passing data. They introduces indirect transfer of control, high coupeling and hinders the ability of the design to be decomposed.

"Sharing data inside the application using global variables will also help you minimize local variable creation and lesser memory usage."

In case you have not noticed: There is nothing to save there, especially nothing that could ever outweigh the cost of labour unnecessarily introduced by the troubles that you are signing up for in the long run, which is caused by side effects that are increasingly hard to spot and even harder to fix because everyone who touches a global variable on which other parts of the system started to rely on.

"Just code at your risk"

Well, do at your risk what ever you fancy, but please refrain from doing so at your employer's, your client's or the general public's risk, since that would be grossly unethical and unprofessional.

And while of course, everyone is entitled to make their own mistakes, may I suggest, that it is better to learn from the experience of those who have been in the field before you - and "Global Variables Considered Harmful" is an insight that dates back to the early 1970es.

Collapse
 
mervinsv profile image
Mervin

Thank you so much. This helps me a lot. I think i will not use global variables anymore or as long as I can manage to make it as a parameter for data sharing.