开发者

Name for factoring out repeated code into separate function

开发者 https://www.devze.com 2023-01-22 16:21 出处:网络
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 factorin

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:

开发者_StackOverflow社区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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号