On Sun, May 27, 2012 at 2:33 PM, Phil Stone <[email protected]> wrote: > In a program I'm making, I have a variable (which stores an instance of > a class) that is declared outside of any functions or classes. However, > I need to be able to call its methods from various class and function > scopes, and nothing but a global variable would let me do that. This > variable is simply what the program is centered around, and must be > accessed and edited by various classes. I'm not sure why a global > variable would be such a bad habit in this case, especially since it is > only one. > > Can I justify using it?
There are circumstances where it is reasonable, see the other replies. However, there's an alternative: define a class which encapsulates all the processing which needs to be done in your script and make the Heap a member of this class. Advantage: you don't have global state and can instantiate the Processor and have all sorts of methods access the Heap member. If you change your program to do multiple calculations in parallel you simply instantiate a Processor for each Thread and need not fear mixing up state of each individual processing. In my experience it is extremely rare that I needed global variables - so rare I can't actually remember the last time I introduced a global variable myself. If at all I use pre defined globals like $stderr and the like. Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/ -- You received this message because you are subscribed to the Google Groups ruby-talk-google group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit this group at https://groups.google.com/d/forum/ruby-talk-google?hl=en
