0
Challenge · 78CS Fundamentals

Encapsulation vs abstraction

OOPused in ~95% of apps

The two most confused words in the interview, and the confusion is understandable because they usually appear together. One is about hiding data so it cannot be corrupted. The other is about hiding complexity so it does not have to be understood. Different problems, different solutions.

Core idea. Encapsulation keeps data private and forces every change through methods that check the rules, so an invalid state is impossible to reach. Abstraction hides how something works behind a simpler description, so callers can use it without knowing.
Playground, this isn't a screenshot
tick the behaviours an item needs
with inheritance
class PlainItem
One class per combination. Three behaviours need 8 classes, and a fourth needs 16.
with composition
traits: []
One item, a list of behaviours. Three behaviours need 3 functions, and a fourth needs 4.

Inheritance grows as two to the number of behaviours. Composition grows as the number of behaviours.

↑ play a little first, then dig in