I have two methods that are near-perfect duplicates. There is of course a code smell. The only thing that changes is the condition to increment a variable.
Language: Java7
private int pathsDFS(int currentDepth, int maxDepth, Airports s, Airports e, Predicate predicate) {
int counter = 0;
if (currentDepth > maxDepth) return counter;
int newDepth = currentDepth + 1;
for (Edge x : g.getNeighboursOf(s)) {
if ( x.getDestination() == e) {
counter++;
}
counter += pathsDFS(newDepth, maxDepth, x.getDestination(), e, predicate);
}
return counter;
}
and
private int pathsDFSB(int currentDepth, int maxDepth, Airports s, Airports e) {
int counter = 0;
if (currentDepth > maxDepth) return counter;
int newDepth = currentDepth+1;
for (Edge x : g.getNeighboursOf(s)) {
if (x.getDestination() == e && currentDepth == maxDepth) {
counter++;
}
counter += pathsDFSB(newDepth, maxDepth, x.getDestination(), e);
}
return counter;
}
What pattern can I apply to remove duplication? I was trying to apply like a Predicate class (calling apply) but that doesn't solve the fact the the values to use are known at runtime inside the for method. Could be considered a strategy pattern the entire for loop?
predicate
in the first method? It is not doing anything. \$\endgroup\$ – Aseem Bansal Jun 16 '14 at 8:59