How to make a variable be visible inside functions?

An OOP design allows you to get around a lot of these issues more logically, and therefore more understandably.

The problem with global variables is what can happen to them in a complex application (read here for complex application, one you are working on after 8pm at night, is due next week, or after your coffee maker has gone out :wink: ) Since the variable has global scope and multiple functions can access them, the ORDER in which various function fire is crucial to the proper functioning of your program.

When you are looking at all the steps in a small encapsulated function, depending on the order in which they fire is OK. (This is why OOP is so valuable because it values taking encapsulation to the extreme, and allows you to use abstractions to simplify the mental work required to understand your code.)

A global variable, however, spreads the steps throughout the entire application, meaning you truly lose the ability to have any reliable understanding of what happens in what order under normal circumstances (and if something doesn’t behave normally… we move into that beautiful realm of ultrascrewed). The result is you manipulate or use a global in one location and “wing and a prayer” that nothing has messed with it in the mean time.

Rather than depending on this dangerous chain of uncertainty, encapsulate populating the value out as a separate function which returns the value as needed. Then any function which needs it can call it and retrieve the value. If a function absolutely needs to have write priveleges you can provide it, but if not, you can expose the variable as a read only and calculate the value inside the function where no one else can see, and you can be sure that no wires are getting crossed.

Ok, so you make it visible to a function via the include, which is what I ended up doing but without the define, but via function calls. For a second I thought you were talking about a way to define a global variable without include which I found from amazing to scary :slight_smile:

I must say this discussion if nothing else has been a very good tutorial about down side of global variables and those who always advocate for object oriented type programming as solution for all :slight_smile:

So frankly I think that the handy function(s) in included files to act as effective global variable providers is the neatest solution.

Just out of curiousity, could you show an example of that?