From: Martin DeMello Date: 2009-01-30T06:40:17+09:00 Subject: Re: proper use of classes On Thu, Jan 29, 2009 at 6:03 AM, Tom Cloyd wrote: > Greetings... > > I'm continuing my learn-to-write-OO-Ruby journey. Had a recent bad > experience trying to convert a complex method to a class. The method gets a > lot of use in my program, and each time it needs to know a lot about the > environment outside itself. I found myself having to write a ton of instance > variable data into the class instance to get it to do its job, before I > called it each time, then read a few more back out to get the results. It > was awful. What had been a one line call was now about 14 lines of code. > Ack! I gave up and converted it back to a method, which simply makes more > sense. I could not find any "class-magic" in this experience - just a lot of > locked doors. One thing that might help is an object to encapsulate the environment that is passed to your method. For instance, a method that worked out whether two particles, given by their initial positions and velocities, would collide, would look something like projectCollision(x1, y1, z1, vx1, vy1, vz1, x2, y2, z2, vx2, vy2, vz2) As a first pass, we'd define a particle class class Particle attr_accessor :x, :y, :z, :vx, :vy, :vz ... end and call our method with projectCollision(particle1, particle2) now particle1 and particle2 are objects of the class Particle, who get their positions and velocities updated at the appropriate places in the code. Your methods that deal with updating the particles' positions and velocities need only pass particle objects around, and the objects themselves act as slates to track changes to their internal data. To a first approximation, I've found that using classes to group and encapsulate function parameters is at least as useful a refactoring as using classes to hold the functions themselves. martin