Day 24 — OOP Interview Scenarios (Python)

Problem statements for practice — attempt them before checking solutions. Focus on design, applying OOP principles, and writing clean Python code.

Practice Problems

1. BankAccount Design

Design a BankAccount class with deposit, withdraw, and transfer functionality. Ensure proper validations and error handling. How would you make it thread-safe?

2. Singleton Class

Implement a Singleton in Python. Explain why singletons might be problematic in testing and how dependency injection helps.

3. Observer/Event System

Create an Event system where functions can subscribe to an event and be notified when it is triggered. Demonstrate with a small example (e.g., a logger or notifier).

4. Strategy Pattern

Design a context class that can use different strategies (algorithms) interchangeably at runtime. Provide at least two strategies (e.g., JSON serializer and XML serializer).

5. LRU Cache

Implement a LRUCache class with get and put methods. Ensure least recently used items are evicted when capacity is reached.

6. Notification System

Design a notification system that can send messages via email, SMS, and push notifications. Make the design extensible for adding new channels later.

7. Plugin System

Design a plugin system for a test runner where plugins can register setup/teardown hooks. Show how new plugins can be added without modifying core code.

8. Immutable Class

Create an immutable class in Python. Show at least two different approaches (e.g., using @dataclass(frozen=True) and __slots__).

9. Composition vs Inheritance

Design an example where composition is better than inheritance. Refactor an inheritance-based design into composition.

10. Refactoring Exercise

You are given a God-class that handles DB, validation, and reporting. Refactor the design by splitting responsibilities into smaller, testable classes.