OOP Notes
Learn the key advantages of OOP including modularity, reusability, maintainability, and how these benefits translate to real-world software projects.
public class InventoryManager { private Database db;
public void updateStock(Order order) { // This module handles ONLY inventory for (OrderItem item : order.getItems()) { db.decrementStock(item.getProductId(), item.getQuantity()); } } }
**Why this matters**: When the payment system has a bug, you know exactly where to look. You don't need to search through thousands of lines of unrelated code.
## 2. Code Reusability
Once you write a well-designed class, you can reuse it across multiple projects. Inheritance and composition allow you to build new functionality on top of existing code without modifying it.class EmailValidator: def __init__(self): self.pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
def is_valid(self, email): import re return bool(re.match(self.pattern, email))
def get_domain(self, email): if self.is_valid(email): return email.split('@')[1] return None
Reused in a registration system
class UserRegistration: def __init__(self): self.email_validator = EmailValidator() # Reusing existing class
def register(self, username, email, password): if not self.email_validator.is_valid(email): raise ValueError("Invalid email address") # ... proceed with registration
Reused in a newsletter system
class NewsletterSubscription: def __init__(self): self.email_validator = EmailValidator() # Same class, different project
def subscribe(self, email): if not self.email_validator.is_valid(email): raise ValueError("Invalid email address") # ... add to mailing list
## 3. Maintainability
OOP code is easier to maintain because changes are localized. When requirements change (and they always do), you typically only need to modify one class rather than hunt through an entire codebase.// If the tax calculation rules change, you only modify ONE class public class TaxCalculator { private double stateTaxRate; private double federalTaxRate;
public TaxCalculator(String state) { this.stateTaxRate = getStateRate(state); this.federalTaxRate = 0.22; // Federal rate }
public double calculateTax(double income) { // Change this method when tax rules change // Nothing else in the system needs to be modified double stateTax = income * stateTaxRate; double federalTax = income * federalTaxRate; return stateTax + federalTax; } }
#include <iostream> #include <string>
class BankAccount { private: double balance; // Cannot be accessed directly std::string owner;
public: BankAccount(std::string owner, double initialBalance) : owner(owner), balance(initialBalance) {}
bool withdraw(double amount) { // Validation prevents invalid operations if (amount <= 0) { std::cout << "Amount must be positive" << std::endl; return false; } if (amount > balance) { std::cout << "Insufficient funds" << std::endl; return false; } balance -= amount; return true; }
double getBalance() const { return balance; } // No setBalance() method — balance can only change through // withdraw() and deposit(), which enforce business rules };
// This method works with ANY shape — even ones not yet invented public double calculateTotalArea(List<Shape> shapes) { double total = 0; for (Shape shape : shapes) { total += shape.area(); // Each shape calculates its own area } return total; }
// You can add a Pentagon class next year without changing calculateTotalArea
class Patient: def __init__(self, name, age, medical_history=None): self.name = name self.age = age self.medical_history = medical_history or []
def add_diagnosis(self, diagnosis): self.medical_history.append(diagnosis)
class Doctor: def __init__(self, name, specialization): self.name = name self.specialization = specialization self.patients = []
def examine(self, patient): print(f"Dr. {self.name} is examining {patient.name}") # ... examination logic
class Appointment: def __init__(self, patient, doctor, date_time): self.patient = patient self.doctor = doctor self.date_time = date_time
| Criterion | Procedural | OOP |
|---|---|---|
| Code organization | Functions & data separate | Data & behavior bundled |
| Reusability | Copy-paste functions | Inheritance & composition |
| Maintenance | Changes ripple everywhere | Changes are localized |
| Team work | Frequent conflicts | Independent modules |
| Security | Global data exposed | Data hidden in objects |
| Scalability | Gets messy at scale | Grows cleanly |
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Advantages of Object-Oriented Programming.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this Object Oriented Programming (OOP) topic.
Search Terms
object-oriented-programming, object oriented programming (oop), object, oriented, programming, introduction, advantages, oop
Related Object Oriented Programming (OOP) Topics