From: Raul Parolari Date: 2007-11-17T08:19:11+09:00 Subject: Re: what is wrong with class variables? (newby) weathercoach@gmail.com wrote: > When people see that I'm using class > variables they ask me why and make a frowny face;). Brian Marick wrote: > There are probably profound philosophical reasons that they're wrong, > but I think the most convincing reason is experience. They were > invented a long time ago (late 70's, I believe), people used them, > and they turned out to cause problems.. The trouble was (is?) that programmers used them to store 'State' that was read and written by several components; the result was that the complexity of the system (the number of possible 'states') grew exponentially with each of those variables (of course, they are so easy to use that they cut down the schedule at the beginning; these problems are never only 'technical'..). Furthermore, in Ruby a 'class variable' is visible across the whole hierarchy of subclasses (a modification done anywhere impacts all); therefore, the potential for trouble is high. Having said that, now for the part that may be controversial: I think that class varibles can be VERY USEFUL, if used correctly; for example, when there is a quasi-static condition to be transmitted to a hierarchy of classes. Rails uses them profusely, for example in action_controller/base.rb, ------ # All requests are considered local by default, so everyone will # be exposed to detailed debugging screens on errors. When the # application is ready to go public, this should be set to false @@consider_all_requests_local = true cattr_accessor :consider_all_requests_local ------- There are many variables like that, which propagate quasi-static conditions to the whole hierarchy. Notice also how they are complemented with a 'class attribute accessor', so that they are accessed via methods (which allows one day to change the implementation, if necessary). Personally, I think that this is simply splendid: maximizing the benefit (cheap distribution of quasi-static info across a hierarchy), minimizing the evils. Rails does even something more interesting: sometimes we want the benefits of a class variable - eg, to inherit its content from the superclass - but we want to be able to change it privately in a class; this is done via the 'class_inheritable_accessor' (which plays a fundamental role to chain modules to the View). In conclusion, I think that very few things in programming are totally 'evil' (or totally 'good'); it all depends from the context, the purpose, and the intelligence of the programmer using them. -- Posted via http://www.ruby-forum.com/.