views:

56

answers:

2

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.

+4  A: 

That's the extract method refactoring.

Jordão
Wow! That was quick, and is exactly what I was looking for. Thanks.
benizi
Welcome! Although your final code is a little bit different than the result of that refactoring. What happened to that `check_only` parameter?
Jordão
This is what threw me at first. The check only is external now, since the check function is separated.
Klay
A: 

I believe this is a basic case of OO modularity. You're separating out two discrete processes that don't necessarily have to go together.

Klay