Encapsulation | 15
Why Abstractions Are Important
We can see two key reasons that abstractions are important for both OOP and
Design Patterns. Rather than being dogged by minutiae of the problem, abstraction
helps to focus on what parts, independent of their details, are required to solve the
problem. Does this mean that you ignore the details? Not at all. Rather, the details
are handled by adding them just when they’re needed. For instance, in the example
in the previous section, the exact video file is unimportant. All that’s important is
that some video name (a detail) be provided when we’re ready to play it. We don’t
need to build a theater around a single movie. Likewise, we don’t need to build a
class around a single video file.
The second advantage of abstraction is flexibility. If you’re thinking that in the previ-
ous section the Example 1-2 was easier and took less code and classes, you’re right.
However, suppose you want to place four videos on the stage. Then, all you would
need to do is to create four instances using the abstract class instead of re-writing
three more classes. In other words, the second method using abstraction is more flex-
ible. In addition to adding more videos instances, we can easily change the video file
we choose to play.
Encapsulation
Encapsulation is what makes a code object an object. If you have a tail, four legs, a
cold nose and a bark, you do not have a dog. You just have a collection of parts that
make up a dog. When you bring all of the doggy parts together, you know that each
part is a part but collectively, you do not think of parts but a realitysui generis. That
is, a dog is an object unto itself and not doggy parts that happen to hang together.
Encapsulation has a similar effect on a collection of operations and properties.
Encapsulation has been used synonymously with other terms such ascomponentand
module. In the context of OOP, encapsulation is often calleda black box, meaning
you can see it do certain things but you cannot see the inner workings. Actually, a lot
of things we deal with all the time are black boxes, such as our dog. We can see the
dog do a lot of different things, and we can interact with the dog. However, we really
don’t know (or usually care) about how the physiology of the dog works—dogs are
not transparent. They’re black boxes.
The good thing about the concept of a black bo xis that we don’t have to worry
about the inner workings or parts. We just have to know how we can deal with it,
secure in the knowledge that whatever makes the black bo xwork is fine as long as it
works as we think it should.