Java method overload
I have 2 alternatives to implement a calculation method, and I am wondering what would be the better approach.
The method needs some int and double parameters and开发者_高级运维 (in some cases) a special flag to do some different calculation.
In the first example, I could call the method with 'calculateFoo(1, 2.0d)' to have the boolean flag == FALSE.
In the second example, I always have to set the boolean flag (even if I do not need it)
Method 1: (here I'm using the '...' as an 'method overloading' parameter)
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;
}
Method 2: (this is the 'common' approach)
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;
}
both your methods have code smell, boolean flags suck
here is my suggestion
public SomeObject calculateFoo(int pIntValue, double pDoubleValue) {
// normal calculation here
}
public SomeObject calculateFooSpecial(int pIntValue, double pDoubleValue) {
// special calculation here
}
Consider the following pattern:
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;
}
}
Generally it's better to use an enum instead of a boolean flag. It makes your code more readable and is just as fast.
I noticed you considered using varargs. If you want to use more flags consider using an EnumSet to pass a set of flags to the method. If you want to pass 0 or 1 flags, varargs is even more definitely an antipattern.
Do the second variant as it is more explicit. Varargs would allow you to pass more than one boolean which are then not used. Better you explicitly define the interface using a single boolean.
If you want to have a default for the boolean flag use another overload:
public SomeObject calculateFoo(int pIntValue, double pDoubleValue) {
return calculateFoo(pIntValue, pDoubleValue, false);
}
I would define another one method with just two parameter to perform default calculation.
public SomeObject calcFoo(int, double) {
....
}
public SomeObject calcFoo(int i, double d, boolean b) {
if(b) {
....
} else {
return calcFoo(i, d);
}
}
精彩评论