简体   繁体   中英

Why are global variables discouraged in a Java program?

I'm new to programming and I'm quite confused why some people are insisting that global variables are bad. I'm currently writing a program with several classes and a lot of checking and rewriting data stored in variables. I found global variables extremely helpful since I don't need to create a getter and setter for each of the local or possibly class variables. By using global variables as bridges between different classes, I found it surprisingly easy to exchange information between those classes.

But again, I'm quite new to programming and I would be much appreciated if someone could explain to me why this is not advisable to do.

Edit : My apologies. I didn't know that global variables and public class variables are completely different and apparently I misidentified public fields as global variables. You never know how silly of a mistake a beginner programmer can make Lol. Thanks everyone for bringing this to my attention.

The problem is that this practice doesn't scale. As projects get more complex or involve more collaborators, globals invite confusion and bugs as it becomes ever harder to keep track of possible side effects. "The left hand doesn't know what the right hand is doing." Or at least, not without considerable testing and research--adding to the cost of maintenance.

You might peruse a book on best practices, such as "Clean Code" by Robert C. Martin, a classic.

A similar situation arises in security, where we have the concept of granting least privileges .

It's going to take a while to really understand object-oriented programming. The big issue with global variables is the same issue with getters and setters, making anything public or extending a superclass. You're making a commitment to every piece of code that touches a global variable, or a setter or a getter that /you will not change the implementation/ that you've exposed. Right now that's fine. Two years from now, what happens when 100,000 lines depend on that variable and now you realize that your “int x, y” implementation detail really should be “int x, y, z”? Feel like spending the weekend tracking down and fixing thousands of references to this code? Now imagine this problem multiplied by all the instances of state you've needlessly exposed to users of your code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM