如何避免在 Java 中使用方法选择器参数(标志/布尔参数) [英] How can I avoid using method selector arguments (flag/boolean arguments) in Java

查看:21
本文介绍了如何避免在 Java 中使用方法选择器参数(标志/布尔参数)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚完成了清洁代码戒律之一是避免将布尔参数作为函数选择器传递,例如,

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

取而代之的是:

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;
}

但是在更复杂的方法中,拆分方法意味着大量重复代码,我该怎么办?

这里应该做什么:

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);

}

推荐答案

你必须区分公共API内部API.

对于公共 API,您确实应该避免此类选择器参数.但是对于内部 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;
}

这篇关于如何避免在 Java 中使用方法选择器参数(标志/布尔参数)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆