From: "weathercoach@..." Date: 2007-11-17T08:05:05+09:00 Subject: Re: what is wrong with class variables? (newby) > > 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 Brian. Now I understand the frowny faces. Your explanation is great in that I don't have to be a skilled programmer to comprehend your point. Thank you very much for breaking it down like this. I'll see if my boss will get me the book;) Thanks again. G. > 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 slantwww.exampler.com,www.exampler.com/blog, twitter.com/marick