Refactoring to Increase Cohesion
You'll learn: How to reorganize your code so each class or module focuses on one clear, well-defined purpose.
The Core Idea
High cohesion means everything inside a class or module works toward the same goal. When a class tries to do too many unrelated things, it has low cohesion—like a toolbox containing hammers, birthday candles, and tax documents. Refactoring to increase cohesion means splitting up these "junk drawer" classes so each one has a focused responsibility.
Three Key Techniques
Extract Class: When a class handles multiple unrelated responsibilities, pull out one responsibility into a new, dedicated class. If your Customer class manages both customer data and email notifications, extract an EmailNotifier class.
Move Method: When a method in one class uses data or collaborates heavily with another class, move that method to where it belongs. If Order.calculateShippingCost() only uses Address data, consider moving it to the Address class.
Feature Grouping: Identify which methods and data naturally belong together. Methods that work on the same data or contribute to the same feature should stay together; everything else should be questioned.
Why It Matters
Highly cohesive modules are easier to understand, test, and modify. When everything in a class serves one purpose, you know exactly where to look when requirements change. It's the difference between a kitchen drawer organized by purpose (utensils, tools, wraps) versus one random jumble.
Key Takeaway: Use extract class, move method, and feature grouping to ensure each module does one thing well—high cohesion makes your code predictable, maintainable, and aligned with the Single Responsibility Principle.