I have trouble finding way to correctly refactor this code so that there would be as little duplicate code as possible, I have a couple of methods like this (pseudocode):
public List<Something> parseSomething(Node n){
List<Something> somethings = new ArrayList<Something>();
initialize();
sameCodeInBothClasses();
List<Node> nodes = getChildrenByName(n, "somename");
for(Node n:nodes){
method();
actionA();
somethings.add(new Something(actionB());
}
return somethings;
}
methods sameCodeInBothClasses() are same in all classes but where it differs is what hapens in for loop actionA() and it also adds an element to the List of different type.
Should I use Strategy pattern for the different parts inside loop?
What about the return value (The type of list differs), should the method return just List<Object> that I would then cast to appropriate type? Should I pass the class I want to return as parameter?
The applicable design pattern is Template Method, rather than Strategy.
About the different type of items, I would try genericizing
parseSomethingfirst, like this:This may not work for you straight away though. You may need to move the generic parameter to the class level.
Returning
List<Object>will not work, as generic collections are invariant: forany two distinct types
Type1andType2,List<Type1>is neither a subtype nor asupertype of
List<Type2>(even ifType1andType2are related, i.e. one is a subtype of the other!). See an earlier answer of mine for more details on this.So if all else fails, the quick and dirty solution would be indeed to use a non generic
List.