Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I write classes that don't rely on "global" variables?

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?

like image 774
Joel Avatar asked May 24 '10 15:05

Joel


1 Answers

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 is perfectly acceptable.

The variables are confined within your class, so they are not "global."

See Encapsulation.

like image 89
Robert Harvey Avatar answered Sep 17 '22 13:09

Robert Harvey