将重复代码分解为单独函数的名称
我正在尝试寻找有关特定代码重构模式的研究/建议,但我发现很难找到它,因为我不确定它是否有一个好名字。它与分解重复的代码非常相似,只不过代码一开始就没有重复:它只是隐藏在更大函数的条件分支中,可以通过该函数的参数访问。
在伪代码中,之前:
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)
之后:
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)
编辑:添加了示例调用。不清楚删除的参数是否是重构的一部分。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
用于将重复代码分解为单独方法的模式称为“提取方法重构” 。
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.