This is the 32nd Step towards gaining the Programming Enlightenment series. If you didn’t learn the 31st Step, read it.
Encapsulation is an OOP information-hiding mechanism used to hide the values or state of a structured data object.
Also, encapsulation is gathering all operations on the object’s state into the object’s interface, and only those operations.
Objects in real-world or OOP share two characteristics: They have state and behavior.
Example; For Dog Object have
- State -> (name, color, breed, hungry) usually defined as variables or field.
- Behavior -> (barking, fetching, wagging taile) usually defined as accessor methods.
Why encapsulate behavior, not just state?
Let’s say we have three classes: Customer, Order and Item.
customer.validateCredit(item.price()) //Here price of item is delegated to item object, whereas validateCredit is deligated to customer object. If condition fails, an exception can be thrown and purchase aborted.
So, if we don’t encapsulate behavior, we might decide to wrap all the business rules into an object, as OrderManager or OrderService, where Order, Customer and Item are fields or variables.
We tie those fields with logic in a one large mess, following procedural approach and losing the OOP approach, hence breaking encapsulation.
TL;DR Realize the power of encapsulation and allow OOP paradigm to dig deep within the codebase.
Go to 31st Step
Go to the 32nd Step.
References:
- 97 things Every Programmer Should Know ~ Git Book
- 97 Things Every Programmer Should Know ~ Paperback
- What is an Object? Oracle
- What is Encapsulation? Wiki
- What is OOP? Wiki