DEV Community

Eamon Keane
Eamon Keane

Posted on • Originally published at eamonkeane.dev on

Software Abstraction vs. Encapsulation

Software Abstraction vs. Encapsulation

I'm currently making my way through the highly commended book Code Complete by Steve McConnell.

This book consistently ranks in the top 5 books for software developers. I've only just started to read it but it's plaudits are well deserved. There's so much value packed into it.

I'm going to distill what I believe the essential differences between Abstraction and Encapsulation.

Abstraction

Software Abstraction vs. Encapsulation
Photo by Ash Edmonds / Unsplash

Steve describes abstraction as the ability to engage with a concept while safely ignoring some of its details. He goes on to say that anytime we work with an aggregate of some sort we're working with an abstraction. We don't say that we're going to go visit someone's combination of glass, wood, concrete and nails, we say that we're going to visit someone's house. We've just performed an abstraction. We ignore the little things and lump them into the concept of a house.

Good classes allow us to concentrate on working with their interfaces (the pieces we "see") and ignoring how they work under the hood. We might have a class named SchoolManager and it has a method named EnrollStudent.

When we work with an instance of the SchoolManager class and we want to enroll a student, we can concentrate on working with the EnrollStudent method and trust that it does what its supposed to. We can ignore irrelevant details at this level.

Under the hood, EnrollStudent might add a student to a collection but when working with the StudentManager object, we don't care about that.

Most real world objects are abstractions. Think of the objects around you, they're all abstractions.

Steve finishes off by saying that Abstraction allows you to take a simpler view of a complex concept.

Encapsulation

Software Abstraction vs. Encapsulation
Photo by Sophie Dale / Unsplash

Where abstraction says 'You can look at an object at a high level of detail.' Encapsulation goes on to say that 'you aren't allowed to look at an object at ANY OTHER level of detail. '

The author uses the analogy of a house and a door. Encapsulation is a way of saying that you can look at the outside of a house and you can see that there's a door. However, you can't get close enough to make out how the door is made or what material it's made off. Encapsulation prevents you from seeing the detail of the door. This is by design and for your own good!

Encapsulation helps to manage complexity by forbidding you to look at the complexity.

If this book sounds like it might be useful to here's an affiliate link you can use:

Code Complete by Steve McConnell.

This helps with the cost of running my blog.

Top comments (0)