Part 3 of 7 · 2 min read
Three groups, one class
The Employee example.
CA uses a payroll program. An Employee class has three methods. calculatePay is wanted by the finance department. reportHours is wanted by the human resources department. save is wanted by the database administrators. Each method belongs to a different actor, but all three live in one class.
The danger shows up when two of the methods share a helper. Here is a small version in Java, using made up numbers. An employee earns 20 per hour. Hours above 40 count as overtime and pay one and a half times.
class Employee {
final double rate;
final int hours;
Employee(double rate, int hours) { this.rate = rate; this.hours = hours; }
int regularHours() { return Math.min(hours, 40); }
double calculatePay() {
return regularHours() * rate + (hours - regularHours()) * rate * 1.5;
}
String reportHours() {
return regularHours() + " regular, " + (hours - regularHours()) + " overtime";
}
}
For 45 hours this class gives a pay of 950 (40 times 20, plus 5 times 30) and the report "40 regular, 5 overtime". Both methods call regularHours(), because the developer saw the same code twice and joined it.
Now finance changes the rule: overtime starts after 38 hours for pay purposes. A developer edits regularHours() to use 38. Pay becomes 970, which is what finance wanted. But the HR report now says "38 regular, 7 overtime". HR never asked for that, and may not notice for weeks. A change for one actor broke a result for another.
CA calls this accidental duplication: two pieces of code look the same today, but they belong to different actors and will drift apart. Sharing them was a trap.
Accidental duplication
Accidental duplication is code that looks the same only by chance of the present, because the two copies serve different actors and will need different changes later.
Example: regularHours() shared by the pay method and the report method.
Check yourself: 1. Which method in the example belongs to HR? 2. After finance's change, what does the HR report show for 45 hours? 3. Why was joining the two copies of the code a mistake here?