From: Brian Marick Date: 2007-11-17T06:45:26+09:00 Subject: Re: what is wrong with class variables? (newby) On Nov 16, 2007, at 2:55 PM, weathercoach@gmail.com wrote: > So as I'm trying to get a better understanding of ruby I ask what's > wrong with class variables? 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. They made it harder to write a program, leave it, come back to it, extend it, and have that work. They made confusing bugs more likely. And (often) it's just as easy to do without them. One lesson I've learned the hard way is that it's almost always better to use an instance than a class. For example, you have this: > one = Simple.append("fred") > puts Simple.return_var > two = Simple.append("tony") > puts Simple.return_var I'd be tempted to do that if I knew -- absolutely knew -- that there was never going to be more than one Simple. But I've learned to prefer something like this: simple = Simple.new one = simple.append("fred") puts simple.return_var two = simple.append("tony") puts simple.return_var Why? Because almost *every* *time* I use the class instead of an instance, I end up regretting it. Notice that if you use the instance, you'll change your implementation of Simple to this: class Simple def initialize @var = [] end def append(i) @var << i end def return_var @var end end Class variable is gone. And you can start taking advantage of other Ruby features. For example, you can use attributes to avoid writing some code: class Simple attr_reader :var # replaces the def of return_var def initialize @var = [] end def append(i) @var << i end end In what I guess you'd call the modern style of coding, people write tests before writing the code. What that does is make long-term unpleasantness into immediate unpleasantness. For example, class variables make classes hard to test, so testing encourages you not to use them. Now for the blatant plug: I describe this style of coding in _Everyday Scripting with Ruby_ . ----- Brian Marick, independent consultant Mostly on agile methods with a testing slant www.exampler.com, www.exampler.com/blog, twitter.com/marick