-4

I found this previous question that addresses the issue. The question is: How do I deal with global variables in existing legacy code (or, what's better, global hell or pattern hell)?

My question is to ask for more detail in how to accomplish the last part of the solution. The most popular solution says: "Over time you can hope to kick the can all the way to the end of the road, by removing all direct knowledge of the global instance from every class, and finally getting rid of the global instance..."

I have a project where I have grouped globals into a class, as suggested in the solution. I am also passing an instance of this global class into the other classes that need the globals. What I don't understand is how to accomplish that last step to "finally getting rid of the global instance...".

Bart van Ingen Schenau
  • 71,712
  • 20
  • 110
  • 179

1 Answers1

2

Under the assumption that the parameters of this "global" class have a different name than the global instance itself, if you do a search over all your code, the name of this global instance should appear only in 2 places:

  1. Where you declare the instance
  2. In the function where you pass it to the top-level objects that need access to it (or need to pass it down to objects that need access).

Once you have reached that point, you can move the instance declaration into the class that the using function is a member of, or even into the function itself if exiting the function means exiting the application. That is what is meant by "getting rid of the global instance", as after this action it is no longer global.

Bart van Ingen Schenau
  • 71,712
  • 20
  • 110
  • 179