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);
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With