Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I avoid using method selector arguments (flag/boolean 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);

}

like image 739
LimaNightHawk Avatar asked Feb 13 '23 20:02

LimaNightHawk


1 Answers

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;
}
like image 130
Seelenvirtuose Avatar answered Feb 15 '23 10:02

Seelenvirtuose