The difference between encapsulation and abstraction seems to trouble some people, which is something I find rather odd. While both are concepts important to object oriented design, and while both are complementary to one another, they are two different concepts. In this article I will explain briefly what encapsulation and abstraction are, and how they interact with, and complement, each other.
First, a few words about each of abstraction and encapsulation:
- The use of abstraction in software design is similar to its use in maths. It involves representing a physical thing or a concept in terms of its essential properties and behaviour. This way, such a thing, be it a concept or something that has physical existence, can be dealt with in a way suitable for modelling the way the real world behaves.
- Encapsulation is a tool – that is, a tool in the intellectual sense – for drawing boundaries around implementations. One reason for this is to allow implementations to change without affecting the outside world. Another reason, perhaps more important, is its usefulness in structuring the design of a system. To further emphasise the organisational usefulness of encapsulation, consider that it allows the implementation to be tested in isolation, without integration with the rest of the system. A simple function is one example of a unit of encapsulation – that is, as long as it does not use any global variables or any other kind of globally accessible resource. In passing note that this is why global variables are such a bad idea – they compromise the boundaries of encapsulation.
In my articles Accessing Object Properties While Respecting Encapsulation and Updating Object Properties While Respecting Encapsulation, I used a Circle
class to illustrate the querying and updating of object properties. The class implements a Circle
abstraction, in that Circle
is manifested in a computer model by being represented as a combination of state and behaviour. Encapsulation is the instrument that permits the Circle
to expose its state to the outside world in a way that keeps the public perception of its state separate from the way its state is implemented. For example, the Circle
exposes a public radius property, but the implementation could be in terms of the diameter – requiring a calculation in the background when the radius is queried.
Abstraction and encapsulation are each complex topics in their own right, far more so than might be apparent when these concepts are first encountered. I hope this short article has helped to shed some light on the difference between encapsulation and abstraction.
1 Comment
I’m curious to find out what blog system you’re using? I’m experiencing some minor security issues with my latest website and I would like to find something more secure. Do you have any suggestions?