In this lesson, you will learn how to break down "God objects"—monolithic classes that attempt to manage too many responsibilities—into smaller, focused building blocks.
The Problem of Monoliths
As your application grows, a class often becomes a "God object" by accumulating diverse behaviors like data validation, persistence, notification logic, and complex business calculations. This makes the class fragile; changing how you save data might accidentally break your business logic.
From Monolith to Modularity
Instead of a single class that does everything, aim for a class that orchestrates specialized components. We achieve this by applying the patterns we've covered, such as Dependency Injection, the Strategy Pattern, and Composition.
Consider a UserManager that handles password hashing, database storage, and email notifications:
# Instead of one massive class, decompose it:
class PasswordHasher:
def hash(self, password): ...
class UserDatabase:
def save(self, user): ...
class UserManager:
def __init__(self, hasher: PasswordHasher, db: UserDatabase):
self.hasher = hasher
self.db = db
def register_user(self, user):
user.password = self.hasher.hash(user.password)
self.db.save(user)
By delegating these tasks to separate classes, UserManager becomes an orchestrator. This architecture offers three major benefits:
- Isolated Testing: You can test your
PasswordHasherlogic in total isolation from the database code. - Swappability: If you decide to switch from an SQL database to a NoSQL one, you only need to inject a different implementation that satisfies the interface, leaving your business logic untouched.
- Reduced Complexity: Each class now has a single, clearly defined purpose (following the Single Responsibility Principle), making your codebase easier to navigate.
When refactoring, look for "and" in your class names or methods—like OrderProcessorAndNotifier. If you see it, that's a signal to extract those responsibilities into their own modular classes and inject them as dependencies.
Key Takeaway: Replace monolithic classes with modular architectures by delegating specific responsibilities to independent, swappable components via composition and dependency injection.