When I took my first programming course in university, we were taught that global variables were evil & should be avoided at all cost (since you can quickly develop confusing and unmaintainable code). The following year, we were taught object oriented programming, and how to create modular code using classes.
I find that whenever I work with OOP, I use my classes’ private variables as global variables, i.e., they can be (and are) read and modified by any function within the class. This isn’t really sitting right with me, as it seems to introduce the same problems global variables had in languages like C.
So I guess my question is, how do I stop writing classes with “global” variables? Would it make more sense to pretend I’m writing in a functional language? By this I mean having all functions take parameters & return values instead of directly modifying class variables. If I need to set any fields, I can just take the output of the function and assign it instead of having the function do it directly. This seems like it might make more maintainable code, at least for larger classes. What’s common practice?
I agree that class member variables can sometimes feel like globals in some ways. I find that the important thing is to keep the classes small, then each variable can only be accessed from a limited number of places. If you have only a few huge classes, the difference between a member variable and a global can sometimes be limited.
Passing around too many parameters can sometimes be an issue as well, if you’re desperate to avoid all member variables you can easily end up with too many parameters that makes the code difficult to follow.