2026-06-09 / Fundamentals
Object Orientation and Design Principles: Encapsulation, Inheritance, and Code Smells
Object orientation is about responsibility assignment and invariant protection, not mechanically placing data and methods into classes.
FundamentalsAlgorithmProgramming
Object Orientation and Design Principles: Encapsulation, Inheritance, and Code Smells
The value of object orientation is placing behavior near the data and rules it owns, so objects can protect their invariants.
Core Concepts
Encapsulation hides internal state and exposes meaningful operations. Inheritance expresses stable is-a relationships, but deep inheritance makes change hard. Composition is often easier to evolve.
classDiagram
class Order {
+Submit()
+Cancel()
-EnsureCanSubmit()
}
class Money {
+Amount
+Currency
}
Order --> Money : total
Code Smells
- God Class: one class owns everything.
- Feature Envy: a method mostly manipulates other objects.
- Long Parameter List: behavior lacks a proper object.
- Primitive Obsession: all concepts are expressed as strings or numbers.
Best Practices
- Ask who should own the rule.
- Keep invariants inside objects.
- Prefer composition and use inheritance carefully.
- Fix responsibility boundaries when smells appear.