I have the following code that is duplicated and I'd like to only write it once (please note that it's just a sample of what I want to achieve):
public class A {
public void doSomething(StringBuffer additional, int start, int end) {
try {
StringBuilder strBuilder = callMethodA();
strBuilder.append(additional, start, end);
B.doSomething(strBuilder, additional, start, end);
} catch (Exception e) {
// do something
}
}
public void doSomething(StringBuilder additional, int start, int end) {
try {
StringBuilder strBuilder = callMethodA();
strBuilder.append(additional, start, end);
B.doSomething(strBuilder, additional, start, end);
} catch (Exception e) {
// do something
}
}
...
}
public class B {
public static void doSomething(StringBuilder strBuilder,
StringBuilder additional, int start, int end) {
// Do some code specific to "additional" StringBuilder
...
}
public static void doSomething(StringBuilder strBuilder,
StringBuffer additional, int start, int end) {...}
// Do some code specific to "additional" StringBuffer
...
}
As you can see, the code is identical except from the fact that the "additional" parameter is in the first method of class A
a StringBuilder
and in the second a StringBuffer
.
How can I modify my code so it will allow me to avoid duplication? The logic in class B
is different for a StringBuffer
and for a StringBuilder
.
I cannot use AbstractStringBuilder
since it's a protected class.
I'm using Java 6.
Thanks