LimaNightHawk LimaNightHawk - 5 days ago 6
Java Question

How can I avoid using method selector arguments in Java

I've just finished Clean Code and one of the precepts is to avoid passing boolean arguments as functional selectors, e.g.,

Instead of this:

public double calculateWeeklyPay(boolean overtime) {
double pay = calculatePay();
if (overtime) {
return pay *= 1.5;
}
return pay;
}


We should do this, and let the consumer call the appropriate method:

public double calculateWeeklyPay() {
return calculatePay();
}

public double calculateWeeklyPayWithOvertime() {
double pay = calculateWeeklyPay();
return pay *= 1.5;
}


But what should I do in more complicated methods where splitting up the method will mean lots of duplicate code?

What should be done here:

public double calculateWeeklyPay(boolean overtime) {

double pay = calculatePay();
pay = modifyPay1(pay);
pay = modifyPay2(pay)
pay = modifyPay3(pay)
if (overtime) {
pay = pay *= 1.5;
}
pay = modifyPay4(pay);
pay = modifyPay5(pay);
pay = modifyPay6(pay);


}

Answer

You have to distinguish between the public API and the internal API.

For the public API you really should avoid such selector arguments. But for an internal API (the private methods) it is an appropriate mechanism for implementation. So make it like this:

public double calculateWeeklyPayWithOvertime() {
    return calculateWeeklyPay(true);
}

public double calculateWeeklyPayWithoutOvertime() {
    return calculateWeeklyPay(false);
}

private double calculateWeeklyPay(boolean overtime) {
    double pay = calculatePay();
    if (overtime) {
         pay *= 1.5;
    }
    return pay;
}
Comments