I actually think that passing the struct to every function is a better (a better encapsulated, lower coupling) approach that the other solutions. But what you need to do is move forwards to o-o. If you have your C-style struct, then it's pretty easy to move it to a class with methods.
Then you don't have to pass the struct on from function to function. The member of the same class will have access to the same member data. |
I am using an OO(-ish) structure. All the program logic is encapsulated in classes. The global variables are the read-in data and some parameters. The read-in data is needed everywhere, the parameters in specific functions of nearly every class. The problem with the first is
frequency of use. Adding a class method call to each access of the data is extra work, both for the programmer [me] as the processor. For the parameters, I'd have to pass the object containing the parameters to every function, even if only one single function requires it, because the function call is deeply nested in other function calls.
I'd like to stress once again that
the actual problems with Globals don't apply here. Nobody else will look at the code, let aside change it. I'm careful with my naming policy to make sure there will never be a local variable with the same name as a global. The only problem is that several cpp files will cause those global variables to be declared twice. If possible, I'd like to fix it in a "good practice" way, but if a dirty fix will do what I need, I'll gladly take it. Rather than just calling something "bad practice", I'd love to hear pro's and con's so I can make the decision myself [as well as learn something].
The class-with-statics is a possible solution to my problem: it's "safe" from multi-declaration, yet can be accessed everywhere without having to pass it to places that don't need it. "They can be accessed from too many places" is not a downside to me. It's a solo-project and I'm confident I can make sure I only access it in the correct places. If there are other downsides, feel free to mention them. I'm still trying to make an educated choice here, I'm just not going to accept a straight "bad practice" excuse without knowing
why.