Thursday, June 10, 2010

When to Overload

When there is a general, non-discrimitive description of the functionality that can fit all the overloaded methodes.

public class StringBuffer {
StringBuffer append(String str) { ... }
StringBuffer append(boolean b) { ... }
StringBuffer append(char c) { ... }
StringBuffer append(int i) { ... }
StringBuffer append(long l) { ... }
StringBuffer append(float f) { ... }
StringBuffer append(double d) { ... }
// ...
}

When all the overloaded methods offer exactly the same functionality, and some of them provide default values for some of the parameters.

public class String {
public String substring(int i, int j) {
// base method: return substring [i .. j-1]
}
public String substring(int i) {
// provide default argument
return substring(i, length - 1);
}
// ...
}

No comments:

Post a Comment