Search code examples
design-patternslanguage-agnosticrefactoring

Name for factoring out repeated code into separate function


I'm trying to find research/advice on a particular code refactoring pattern, but I'm finding it hard to locate, since I'm not sure whether there's a good name for it. It's very similar to factoring out repeated code, except the code wasn't repeated in the first place: it was just stashed away in a conditional branch of a larger function, accessible via a parameter of that function.

In pseudocode, the before:

function frobnicate(id, check_only = false) {
    if id cannot be frobnicated
        return false
    if check_only
        return true
    // frobnicate id
    return true
}

// example calls:
okay_to_frobnicate = frobnicate(id, true)
frobnicate_success = frobnicate(id)

After:

function can_be_frobnicated(id) {
    if id cannot be frobnicated
        return false
    else
        return true
}

function frobnicate(id) {
    if not can_be_frobnicated(id)
        return false
    // frobnicate id
    return true
}

// example calls:
okay_to_frobnicate = can_be_frobnicated(id)
frobnicate_success = frobnicate(id)

Edit: added example calls. Wasn't clear that the removed parameter was part of the refactoring.


Solution

  • The pattern used to factor out repeated code into separate methods is called "extract method refactoring".