繁体   English   中英

Java方法重载

[英]Java method overload

我有2种实现计算方法的替代方法,我想知道哪种方法更好。

该方法需要一些int和double参数,并且(在某些情况下)需要一个特殊的标志来进行一些不同的计算。

在第一个示例中,我可以使用“ calculateFoo(1,2.0d)”调用该方法,使其具有布尔标志== FALSE。

在第二个示例中,我总是必须设置布尔标志(即使我不需要它)

方法1:(这里我使用“ ...”作为“方法重载”参数)

public SomeObject calculateFoo(int pIntValue, double pDoubleValue, boolean... pDoSpecialStuff) {

    if (pDoSpecialStuff.length == 0 || pDoSpecialStuff[0] == false) {
        // method was called without boolean flag or boolean flag was set to FALSE

        // do some calculation stuff
        // ...
    } else {
        // method was called with boolean flag == TRUE

        // do some other calculation stuff
        // ...
    }

    return SomeObject; 
}

方法2:(这是“常见”方法)

public SomeObject calculateFoo(int pIntValue, double pDoubleValue, boolean pDoSpecialStuff) {

    if (pDoSpecialStuff == false) {
        // method was called with boolean flag == FALSE

        // do some calculation stuff
        // ...
    } else {
        // method was called with boolean flag == TRUE

        // do some other calculation stuff
        // ...
    }

    return SomeObject; 
}

您的两个方法都有代码气味,布尔标志很烂

这是我的建议

public SomeObject calculateFoo(int pIntValue, double pDoubleValue) {
    // normal calculation here 
}

public SomeObject calculateFooSpecial(int pIntValue, double pDoubleValue) {
    // special calculation here 
}

做第二个变体,因为它更明确。 Varargs允许您传递多个布尔,然后不使用它们。 最好您使用单个布尔值显式定义接口。

如果要为布尔值设置默认值,请使用另一个重载:

public SomeObject calculateFoo(int pIntValue, double pDoubleValue) {
   return calculateFoo(pIntValue, pDoubleValue, false);
}

考虑以下模式:

public ResultType calcFoo( int i, double d ) {
    return calc( i, d, false );
}

public ResultType calcFoo( int i, double d, boolean flag ) {
    if( flag ) {
        ...
        return result;
    }
    else {
        ...
        return result;
    }
}

通常,最好使用枚举而不是布尔标志。 它使您的代码更具可读性,并且速度一样快。

我注意到您考虑使用varargs。 如果要使用更多标志,请考虑使用EnumSet将一组标志传递给该方法。 如果要传递0或1个标志,则varargs绝对是反模式。

我将仅用两个参数定义另一个方法来执行默认计算。

public SomeObject calcFoo(int, double) {
    ....
}

public SomeObject calcFoo(int i, double d, boolean b) {
    if(b) {
        ....
    } else {
        return calcFoo(i, d);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM