Code duplication for just an if condition 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 &gt; 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 &gt; maxDepth) return counter;
    int newDepth = currentDepth+1;
    for (Edge x : g.getNeighboursOf(s)) {
        if (x.getDestination() == e &amp;&amp; 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?
Just add a parameter boolean incrementOnAnyDepth and in your if condition write

if ( x.getDestination() == e &amp;&amp; (incrementOnAnyDepth || currentDepth == maxDepth) )
{
    counter++;
}`