Problem
I am trying to design two methods that filter a list
public List<TypeA> filter(List<TypeA> typeAList) {
//duplicated code
//filter typeAList using some parameters in typeA objects
//return filtered list
}
public List<TypeB> filter(List<TypeB> typeBList) {
//duplicated code
//filter typeBList using some parameters in typeB objects
//return filtered list
}
The problem is both the methods have duplicate code except for the filtering part where I access different parameters inside TypeA and TypeB.
Things I tried so far
- I tried making a generic method like this. But this does not support types other than TypeA and TypeB. Encourages someone to call this method with an unintended type.
public <T> List<T> filter(List<T> genericList) {
//duplicated code
if (T instanceOf TypeA)
//filtering code for TypeA
if (T instanceOf TypeB)
//filtering code for TypeB
//return filtered list
}
- Overload with two methods calling a private generic filter method. I felt this ensures unintended calls to the public method, while still using generics to avoid code duplication.
public List<TypeA> filter(List<TypeA> typeAList) {
//call innerFilter(typeAList)
}
public List<TypeB> filter(List<TypeB> typeBList) {
//call innerFilter(typeBList)
}
private <T> List<T> innerFilter(List<T> genericList) {
//duplicated code
if (T instanceOf TypeA)
//filtering code for TypeA
if (T instanceOf TypeB)
//filtering code for TypeB
//return filtered list
}
- Tried to make the two classes implement a common interface and use that interface as the input parameter to my method. But one of the class is third-party and not under my control.
Help needed
I'm really new to design. Want to understand if my reasoning is right behind the approaches. Also looking for suggestions on alternate best approaches to solve this problem. Thanks in advance.