Re: proper use of classes
- From: Tom Cloyd <tomcloyd@xxxxxxxxxxx>
- Date: Thu, 29 Jan 2009 18:11:15 -0500
Martin DeMello wrote:
On Thu, Jan 29, 2009 at 6:03 AM, Tom Cloyd <tomcloyd@xxxxxxxxxxx> wrote:Wow. Martin that's a fascinating idea. Terrific notion. Gonna try to
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
make use of this. But just the idea is great for me to know aout.
Thanks!
Tom
--
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Tom Cloyd, MS MA, LMHC - Private practice Psychotherapist
Bellingham, Washington, U.S.A: (360) 920-1226
<< tc@xxxxxxxxxxxx >> (email)
<< TomCloyd.com >> (website)
<< sleightmind.wordpress.com >> (mental health weblog)
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
.
- References:
- proper use of classes
- From: Tom Cloyd
- Re: proper use of classes
- From: Martin DeMello
- proper use of classes
- Prev by Date: Zlib.dll
- Next by Date: Re: How to do a for loop...and iterate a set number of times?
- Previous by thread: Re: proper use of classes
- Next by thread: [ANN] rdoc 2.3.0 Released
- Index(es):
Relevant Pages
|