Skip to content

Instantly share code, notes, and snippets.

@songyunlu
Created March 9, 2016 06:37
Show Gist options
  • Save songyunlu/12eadf54960f0ad435ff to your computer and use it in GitHub Desktop.
Save songyunlu/12eadf54960f0ad435ff to your computer and use it in GitHub Desktop.
Refactoring of the code of Feature Envy
public class HourlyPayCalculator {
private int tenthRate;
private int tenthsWorked;
private HourlyPayCalculator(CalculatorBuilder builder) {
this.tenthRate = builder.tenthRate;
this.tenthsWorked = builder.tenthsWorked;
}
public static class CalculatorBuilder {
private final int tenthRate;
public CalculatorBuilder(int tenthRate, int tenthsWorked) {
this.tenthRate = tenthRate;
this.tenthsWorked = tenthsWorked;
}
private final int tenthsWorked;
/* may have other setters for optional variables */
public HourlyPayCalculator build() {
return new HourlyPayCalculator(this);
}
}
private int calculateStraightTime() {
return Math.min(400, this.tenthRate);
}
private int calculateOverTime(int straightTime) {
return Math.max(0, tenthsWorked - straightTime);
}
private int calculateStraightPay(int straightTime) {
return straightTime * tenthRate;
}
private int calculateOverTimePay(int overTime) {
return (int) Math.round(overTime * tenthRate * 1.5);
}
public Money calculateWeeklyPay() {
int straightTime = calculateStraightTime();
int overTime = calculateOverTime(straightTime);
return new Money(calculateStraightPay(straightTime) + calculateOverTimePay(overTime));
}
public static void main(String[] args) {
HourlyEmployee e = new HourlyEmployee("1001", "Jimmy Lu");
e.setTenthRate(30);
e.setTenthsWorked(20);
HourlyPayCalculator calculator = new CalculatorBuilder(e.getTenthRate(), e.getTenthsWorked()).build();
System.out.println(e.getName() + " gets " + calculator.calculateWeeklyPay() + " this week.");
}
}
class Money {
private int pennies;
public Money(int pennies) {
this.pennies = pennies;
}
}
class HourlyEmployee {
private final String id;
private final String name;
private int tenthRate;
private int tenthsWorked;
HourlyEmployee(String id, String name) {
this.id = id;
this.name = name;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public int getTenthRate() {
return tenthRate;
}
public void setTenthRate(int tenthRate) {
this.tenthRate = tenthRate;
}
public int getTenthsWorked() {
return tenthsWorked;
}
public void setTenthsWorked(int tenthsWorked) {
this.tenthsWorked = tenthsWorked;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment