These two examples show the difference between objects and data structures. Objects hide
their data behind abstractions and expose functions that operate on that data. Data structure
expose their data and have no meaningful functions. Go back and read that again.
Notice the complimentary nature of the two definitions. They are virtual opposites. This
difference may seem trivial, but it has far-reaching implications.
Consider, for example, the procedural shape example in Listing 6-5. The Geometry
class operates on the three shape classes. The shape classes are
Object-oriented programmers might wrinkle their noses at this and complain that it
is procedural—and they’d be right. But the sneer may not be warranted. Consider what
would happen if a perimeter() function were added to Geometry. The shape classes would
be unaffected! Any other classes that depended upon the shapes would also be unaffected!
On the other hand, if I add a new shape, I must change all the functions in Geometry to
deal with it. Again, read that over. Notice that the two conditions are diametrically
opposed.
Now consider the object-oriented solution in Listing 6-6. Here the area() method is
polymorphic. No Geometry class is necessary. So if I add a new shape, none of the existing
functions are affected, but if I add a new function all of the shapes must be changed
Again, we see the complimentary nature of these two definitions; they are virtual
opposites! This exposes the fundamental dichotomy between objects and data structures:
Procedural code (code using data structures) makes it easy to add new functions without
changing the existing data structures. OO code, on the other hand, makes it easy to add
new classes without changing existing functions.
The complement is also true:
Procedural code makes it hard to add new data structures because all the functions must
change. OO code makes it hard to add new functions because all the classes must change.
So, the things that are hard for OO are easy for procedures, and the things that are
hard for procedures are easy for OO!
In any complex system there are going to be times when we want to add new data
types rather than new functions. For these cases objects and OO are most appropriate. On
the other hand, there will also be times when we’ll want to add new functions as opposed
to data types. In that case procedural code and data structures will be more appropriate.
Mature programmers know that the idea that everything is an object is a myth. Sometimes
you really do want simple data structures with procedures operating on them.