Search code examples
javaoptimizationcoding-style

Optimize duplicated function with different parameter


I have two exact the same functions and one different function which take a TypeX as parameter. All TypeX has the same parent class Type. The dummy code is like:

public void Append(TypeA item) { //same code }
public void Append(TypeB item) { //same code }
public void Append(TypeC item) { //different code }

I wonder is there a good way to optimize such functions? My code needs to pick up the right function based on the class type, so I can't use the parent class or a generic type here because that will affect TypeC's engagement.

The best thing would be public void Append(TypeA item || TypeB item) but of course there's no such a thing available. Any idea?


Solution

  • Whereas the solutions offered by @erwin-bolwidt would work, I suggest you also consider

    private void baseAppend (TypeParent item) { //same code }
    public void Append(TypeA item) { baseAppend (item); }
    public void Append(TypeB item) { baseAppend (item); }
    public void Append(TypeC item) { //different code }
    

    This method would allow a looser coupling and the potential for specialised logging and expansion in the future