From: Henry Maddocks Date: 2012-05-28T07:40:01+09:00 Subject: Re: Am I justified to use a global variable if it must be used in all scopes? On 28/05/2012, at 12:33 AM, Phil Stone wrote: > Hello, > Ever since I started learning Ruby, I've been strongly discouraged > from using global variables Breaking the 'rules' is fine as long as you understand why the rule exists in the first place. > 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. Being forced to use a global like this is a pretty good indicator that your design is wrong. A good step in the right direction might be to pass your global variable into any methods that need to use it, rather than accessing it directly. This will make it more obvious what is going on and lead to easier to refactor code. > 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? If your program is small then a global variable may be fine, you likely won't come across any problems, and trying to wrap it in a class my be more work than it's worth. As your program grows though the chances that the global var will become a hindrance will increase, but so will the opportunity for you to refactor it out of existence, eg. you may find you need to hold more and more application state that necessitates the creation of an App class, etc. So, yes, use a global if it gets the job done more quickly but don't let it become a habit. Henry