next up previous contents
Next: Polymorphism:Overriding Methods Up: Objects in Perl Previous: Classes

Abtraction

In order to understand and think about abstraction, you need a working definition of the term model. How about, "A model is an approximation of something." If you build a model car, some of the items in the original car will be missing, such as spark plugs, for example. If you build a model house, you wouldn't include the plumbing. Thus, the models that you build are somewhat abstract; the details don't matter, just the form.

Abstraction in object-oriented programming works in the same way. As the programmer, you present the model of your objects to other programmers in the form of an interface. Actually, the interface is just some documentation that tells others how to interact with any of your classes. However, nobody needs to know what your classes really do. It is enough to say that the file object stores the file name and size and presents the information in English. Whether the internal format of the information is compressed, Russian, or stored in memory or on the hard disk is immaterial to the user of your classes.

I recommend that as you design an object or class, you occasionally distance yourself from the work. Try to view the resulting system through the eyes of another to check for inconsistencies and relationships that aren't needed.

You've learned about abstraction in abstract terms so far. Now let's use the Pen class that you created earlier to see a concrete example of abstraction. The Pen class had only one property of its own, the ink color (the rest were inherited). For the sake of argument, the ink color can be "blue,""black," or "red." When a Pen object is created (the mechanism of creation is unimportant at the moment), a specific color is assigned to it. Use "blue" for the moment. Here is a line of code to create the object:

$pen = Pen->new(ew("blue");

Now the Pen object has been created. Do you care if the internal format of the ink color is the string "blue" or the number 1? What if, because you expect to use thousands of objects, the internal format changes from a string to a number to save computer memory? As long as the interface does not change, the program that uses the class does not need to change.

By keeping the external interface of the class fixed, an abstraction is being used. This reduces the amount of time spent retrofitting programs each time a change is made to a class the program is using.


next up previous contents
Next: Polymorphism:Overriding Methods Up: Objects in Perl Previous: Classes
dave@cs.cf.ac.uk