On May 27, 2012, at 5:33 AM, Phil S. wrote:
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?
Avoid using globals as much as possible, variables or constants alike.
The are very hard to look for where they are coming from, impossible to
mock and painful while unit testing in general as they keep persistent
state not being reset for individual test cases.
There are many alternatives to using globals, depending on your
particular case. The best would be to design your app in a way that an
instance can request what it needs from some other instance, possibly
made available at instantiation (or via dependency injection). As others
suggested, you can use a singleton for a class that provides state for
the whole app, which I personally dislike. Or just class methods.
This is what I sometimes use when I need a quick and dirty way to do the
job, to be refactored at the earliest opportunity:
=== main script
class App
def start
…
end
def self.config
@config ||= Config.new
end
end
App.new.start
=== end of main script
=== player.rb
class Player
def config
App::config
end
def perform
return if config.idle_mode?
…
end
end
=== end of player.rb
While behaving exactly as a global config would, it makes it possible to
mock config on several levels in your unit tests. Besides, you can
clearly see where the data is coming from.
Hope this makes sense to you,
Gennady.