Overview
Object-Oriented Programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data (attributes/properties) and code (methods). It aims to implement real-world entities like inclusive objects to make the codebase more modular and intuitive.
Core Concepts
- Class: A blueprint for creating objects.
- Object: An instance of a class.
- Encapsulation: Bundling data and the methods that operate on that data into a single unit (class) and restricting direct access to some of the object’s components (using
private,protected). - Abstraction: Hiding complex implementation details and showing only the necessary features of an object.
- Composition: Building complex objects by combining simpler ones (“has-a” relationship).
Code Examples
class BankAccount {
private _balance: number = 0; // Encapsulation
deposit(amount: number) {
if (amount > 0) this._balance += amount;
}
getBalance() { return this._balance; } // Abstraction
}
const myAccount = new BankAccount();
myAccount.deposit(100);
console.log(myAccount.getBalance()); // 100
// myAccount._balance = 500; // Error: Property '_balance' is private.
Use Cases
- Large Scale Applications: Where modularity is key to managing thousands of files.
- GUI Frameworks: Buttons, Windows, and TextFields are naturally modeled as objects.
- Simulation Software: Modeling physical systems (e.g., a car, a weather system).
Gotchas
- Over-Engineering: Creating deep class hierarchies for simple tasks can make the code rigid and hard to follow.
- The “Banana-Gorilla-Jungle” Problem: In inheritance, you might want a banana, but you get a gorilla holding the banana and the entire jungle (excessive inherited state).
