BIT153 Object Oriented Programming

Object Oriented ProgrammingUnit 1211 min read

Advanced OOP: Design Patterns, UML, STL & Code Optimization

Unit 12 of Object Oriented Programming reviews advanced OOP concepts including design patterns (Singleton, Factory, Observer), UML diagrams (class, sequence, activity), Standard Template Library (STL) containers (vector, map, queue), and code optimization techniques with time/space complexity analysis, preparing studen

TAKEAWAYS:

  • Understand design patterns (Singleton, Factory, Observer) and their real-world applications in Nepalese apps like eSewa (Singleton for session management) and Daraz (Factory for product creation).
  • Master UML diagrams (class, sequence, activity) to model systems like Kathmandu traffic routes or Ncell billing workflows.
  • Apply STL containers (vector, map, queue) to optimize data handling in Pathao’s ride allocation or NEPSE’s stock trading queues.
  • Analyze time/space complexity of algorithms using Big-O notation, critical for optimizing NTC’s network routing or bank loan calculations.
  • Implement code optimization techniques like memoization (used in Daraz’s product recommendation) and lazy evaluation (used in WhatsApp’s message delivery).
  • Compare OOP vs. procedural programming paradigms using a structured table to highlight advantages in modern software development.

1. Design Patterns: Reusable Solutions to Common Problems

Design patterns are proven templates for solving recurring design problems in object-oriented systems. They promote code reusability, maintainability, and scalability. Nepalese tech companies like eSewa (Singleton for user sessions) and Daraz (Factory for product creation) use these patterns extensively.

1.1 Singleton Pattern

Definition: Ensures a class has only one instance and provides a global point of access to it. Use Case: Database connections, logging, configuration settings.

classDiagram
    class Singleton {
        -static instance: Singleton
        +getInstance() Singleton
        -Singleton() private
    }
    Singleton --> Singleton : "Single Instance"

Example: eSewa’s user authentication system uses Singleton to ensure only one session manager exists.

class SessionManager {
private:
    static SessionManager* instance;
    SessionManager() {} // Private constructor
public:
    static SessionManager* getInstance() {
        if (!instance) instance = new SessionManager();
        return instance;
    }
};
SessionManager* SessionManager::instance = nullptr;

Trace:

Step Action instance State
1 First getInstance() call nullptr → new object
2 Second getInstance() Returns existing object

Advantages:

  • Controlled access to a single resource.
  • Reduced memory usage (one instance only). Disadvantages:
  • Global state can lead to hidden dependencies.
  • Thread safety issues if not handled properly.

2. UML Diagrams: Modeling Real-World Systems

Unified Modeling Language (UML) is a visual notation for designing object-oriented systems. Nepal’s NTC (telecom billing) and Ncell (customer service workflows) use UML to model complex systems.

2.1 Class Diagram

Shows classes, attributes, methods, and relationships (inheritance, association, aggregation). Example: Modeling NEPSE’s stock trading system:

classDiagram
    class Trader {
        -id: int
        -name: string
        +placeOrder(stock: Stock) bool
    }
    class Stock {
        -symbol: string
        -price: double
    }
    class Order {
        -orderId: int
        -quantity: int
    }
    Trader "1" --> "many" Order : places
    Order --> Stock : buys/sells

2.2 Sequence Diagram

Shows object interactions over time (e.g., Pathao’s ride allocation). Example: User requests a ride → Pathao matches driver → Ride starts.

sequenceDiagram
    participant User
    participant Pathao
    participant DriverPool
    participant Driver1

    User->>Pathao: Request Ride()
    Pathao->>DriverPool: FindNearestDriver()
    DriverPool-->>Pathao: Driver1
    Pathao->>User: Confirm Ride()
    User->>Driver1: Start Ride()
    Driver1-->>User: Ride Started

2.3 Activity Diagram

Models workflow processes (e.g., Khalti’s payment approval).

flowchart TD
    A["User Initiates Payment"] --> B["Check Balance"]
    B -->|"Sufficient"| C["Deduct Amount"]
    B -->|"Insufficient"| D["Reject"]
    C --> E["Send Confirmation"]

3. Standard Template Library (STL) Containers

STL provides predefined data structures (containers) and algorithms for efficient programming.

3.1 Vector (Dynamic Array)

  • Resizable array (unlike C-style arrays).
  • Use Case: Storing Daraz’s product catalog dynamically.
100201302403504
Vector resizing example: Inserting 35 at index 2 (capacity doubles when full)
#include <vector>
vector<int> products = {101, 102, 103};
products.push_back(104); // Adds 104

Trace:

Step Action products State
1 Initialization [101, 102, 103]
2 push_back(104) [101, 102, 103, 104]

3.2 Map (Key-Value Pairs)

  • Hash table implementation (O(1) average access).
  • Use Case: Ncell’s customer contact database (phone → customer details).
0[object Object][object Object]1[object Object]2—3[object Object]
Hash Table with chaining (h(k) = k.hashCode() % 4)
map<string, string> contacts = {{"9800000000", "Ramesh"}, {"9811111111", "Sita"}};
contacts["9822222222"] = "Hari"; // Adds new entry

Trace:

Step Action contacts State
1 Initialization {"9800000000": "Ramesh", ...}
2 contacts["9822222222"] = "Hari" Adds new key-value pair

3.3 Queue (FIFO)

  • First-In-First-Out structure.
  • Use Case: NTC’s network packet routing.
queue<int> packetQueue;
packetQueue.push(1); // Enqueue
packetQueue.push(2);
int packet = packetQueue.front(); // Dequeue (1)
packetQueue.pop();

Trace:

Step Action packetQueue State
1 push(1) [1]
2 push(2) [1, 2]
3 front() → pop() [2]

4. Code Optimization Techniques

Optimizing code improves performance and efficiency, critical for high-traffic apps like Pathao or Daraz.

4.1 Memoization (Caching)

  • Stores results of expensive function calls to avoid recomputation.
  • Use Case: Daraz’s product recommendation engine (caches user preferences).
unordered_map<int, int> cache;
int fib(int n) {
    if (cache.find(n) != cache.end()) return cache[n];
    if (n <= 1) return n;
    cache[n] = fib(n-1) + fib(n-2);
    return cache[n];
}

Trace:

Step fib(4) Call Stack cache State
1 fib(4) → fib(3) + fib(2) {}
2 fib(3) → fib(2) + fib(1) {2:1, 1:1}
3 Returns cached fib(2)=1 {2:1, 1:1, 3:2}

4.2 Lazy Evaluation

  • Delays computation until necessary.
  • Use Case: WhatsApp’s message delivery (sends only when online).
class LazyMessage {
    string message;
    bool evaluated = false;
public:
    LazyMessage(string msg) : message(msg) {}
    string get() {
        if (!evaluated) {
            // Expensive computation (e.g., encryption)
            evaluated = true;
        }
        return message;
    }
};

5. Time and Space Complexity Analysis

Understanding Big-O notation helps predict algorithm efficiency.

Operation Time Complexity Space Complexity Example Use Case
Linear Search O(n) O(1) Searching NEPSE’s stock list
Binary Search O(log n) O(1) NTC’s sorted customer database
Bubble Sort O(n²) O(1) Small dataset sorting
Hash Table Insert O(1) avg O(n) Khalti’s transaction logging

Example: Ncell’s customer lookup (binary search on sorted list).

vector<int> customers = {1001, 1002, 1003};
int search(int key) {
    int left = 0, right = customers.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (customers[mid] == key) return mid;
        else if (customers[mid] < key) left = mid + 1;
        else right = mid - 1;
    }
    return -1;
}

Trace:

Step left right mid Action
1 0 2 1 customers[1] = 1002 < 1003 → left = 2
2 2 2 2 customers[2] = 1003 == 1003 → Found

6. OOP vs. Procedural Programming: Comparison

Feature OOP Procedural Programming
Approach Objects and classes Functions and data
Reusability High (inheritance, polymorphism) Low (code duplication)
Maintainability High (modular) Low (tight coupling)
Example (Nepal) eSewa (user objects) Old NTC billing scripts
Complexity Better for large systems Simpler for small tasks

In the Real World

  1. eSewa (Singleton Pattern)

    • How: Uses Singleton to ensure only one user session manager exists across the app.
    • Why: Prevents duplicate logins and maintains session consistency.
  2. Daraz (Factory Pattern)

    • How: Uses Factory to dynamically create product objects (ElectronicsProduct, ClothingProduct).
    • Why: Avoids conditional checks for product types, making code cleaner.
  3. Pathao (Observer Pattern)

    • How: Drivers and users are observers to ride updates.
    • Why: Real-time notifications without tight coupling.
  4. Ncell (STL Containers)

    • How: Uses map to store customer IDs → contact details for O(1) lookups.
    • Why: Faster than linear searches in large datasets.
  5. NEPSE (Algorithm Optimization)

    • How: Uses binary search (O(log n)) to find stock prices in sorted lists.
    • Why: Faster than linear search (O(n)) for 10,000+ stocks.

Exam Tip

  1. Design Patterns:

    • Expect questions on Singleton, Factory, and Observer.
    • Draw UML diagrams for class relationships (e.g., inheritance in a bank system).
    • Code trace: Show how Singleton ensures only one instance exists.
  2. STL Containers:

    • Compare vector (dynamic array) vs. list (linked list) in terms of access time.
    • Trace operations: Show step-by-step how map handles insertions/deletions.
  3. Optimization:

    • Memoization: Explain how caching improves performance (e.g., Fibonacci sequence).
    • Big-O: Match algorithms to their complexity (e.g., binary search = O(log n)).
  4. UML Diagrams:

    • Sequence diagrams are common for workflows (e.g., online payment process).
    • Class diagrams often test inheritance and associations.
  5. Real-World Applications:

    • Link theory to Nepalese tech:
      • eSewa → Singleton.
      • Daraz → Factory.
      • Ncell → STL containers.
    • Optimization: Relate to NTC’s network routing or bank loan calculations.

Final Advice:

  • Practice coding STL operations (e.g., vector, map) with traces.
  • Memorize design patterns and their UML representations.
  • Analyze time complexity for sorting/searching algorithms.
  • Use real-world examples (eSewa, Daraz, Ncell) to explain concepts.

Based on the TU BIT syllabus for Object Oriented Programming (BIT153), unit 12.

Discussion

Loading…