Drawing the Line Betwen Objects
Posted by Mark at February 27, 2005 10:12 AM
I used this example of a simple particle system in the Code Literacy course that I teach at ITP. This is a good case of encapsulation at work and raises the question of how much should be encapsulated in one class, or more accurately, how many different kinds of features should be included in one class.
The original code merged the ideas of particle motion and rendering into one object, while these are actually two very different features. As this code is developed, the particle system and rendering code will become very tightly woven together, making it difficult to use the particle system in new contexts.
To make this clearer, look at a real-world example of a component, like the iPod. An iPod does one thing well: play music. But what if I always listen to music while I wash my car, does that mean I want an iPod that dispenses soap, or doubles as a sponge? Not likely, yet this situation arises in code routinely.
The ParticleSystem class contained a Particles array. It could move and render:
ParticleSystem
--------------
Particles[]
move()
render()
I separated out the rendering functionality:
ParticleSystem ParticleRenderer
-------------- ----------------
Particles[] -----> render(Particles[])
move()
I didn't actually create a class called ParticleRenderer, my main applet class functions as the renderer, but the logical next step would be to encapsulate rendering in its own class. The ParticleSystem and ParticleRenderer communicate by passing an array of Particles between them. The value of this approach is that the ParticleSystem now clearly encapsulates one idea: particle motion. We could use that motion to drive animations, build meshes, plot points, draw into an image, or any other specialized use we can think up.
A similar case came up in class with the Jiggler class that takes a Shape as an argument. The ideas are very simple: a Jiggler jiggles a Shape. And the code clearly reflects that: Jiggler.jiggle(crosses[i]).
This isn't just about coding well, it's an exercise in thinking clearly about complex problems. Our brains have evolved over millions of years of perceiving a world of discreet objects. We take for granted that an iPod doesn't also wash the car and that a chair is separate from a table. But in the world of software these structures are not clearly defined. We have to create our own conventions to make usable systems.
Trackbacks
Trackback for this post: http://www.culturekitchen.com/cgi-bin/movabletype/mt-tb.cgi/2779