Part 5 of 7 · 2 min read
Splitting
Separate classes for each actor, one entry point.
The cure is to move each method into its own class, and let each class hold its own copy of the rules it needs. Data stays in a plain class that everyone can read.
class Pay {
double calculatePay(int hours, double rate) {
int regular = Math.min(hours, 38);
return regular * rate + (hours - regular) * rate * 1.5;
}
}
class HourReport {
String report(int hours) {
int regular = Math.min(hours, 40);
return regular + " regular, " + (hours - regular) + " overtime";
}
}
Now Pay answers only to finance and HourReport only to HR. For 45 hours, Pay gives 970 and HourReport still says "40 regular, 5 overtime". Each can change without the other noticing. The small repeat of Math.min is acceptable, because the two lines are accidentally alike and may differ next month.
One cost appears: callers now need to know three classes instead of one. CA suggests two ways to soften this. The first is an EmployeeFacade, a small class that holds no business rules and only forwards each call to the right class. A facade is a front object that hides several others behind one simple door (module 6 of Level 4 covers it in full). The second is to keep the most important method in the original class and let it use the others.
Teams differ on which they prefer. In an interview, say the choice and the reason: a facade keeps callers simple, while keeping the key method in place keeps the number of classes down.
Common mistake
Splitting into one class per method. SRP asks for one class per actor, not one class per function. A class with five methods that all serve payroll is fine.
Check yourself:
1. After the split, what does Pay return for 45 hours?
2. What rules should a facade contain?
3. Why is one class per method the wrong reading of SRP?