跳转到内容

以函数调用取代内联代码

以函数调用取代内联代码(Replace Inline Code with Function Call)把手写的一段逻辑换成对已有函数的调用,那个函数可能来自标准库,也可能是项目里早就有的。 它解决的痛是:同样的功能被手写了一遍,读的人要在心里跑一遍才知道它在干什么,而一个函数名本来一眼就能说清。

一个权限检查函数要判断用户的角色是否在允许名单里,并把一组标签去重。写的人没想起来有现成的写法,用循环手写了。

"""权限与标签:替换前。"""
def can_access(role: str, allowed: list[str]) -> bool:
for r in allowed:
if r == role:
return True
return False
def unique_tags(tags: list[str]) -> list[str]:
result: list[str] = []
for t in tags:
if t not in result:
result.append(t)
return result
if __name__ == "__main__":
print(can_access("editor", ["admin", "editor"]), unique_tags(["py", "ts", "py"]))
# 输出:
# True ['py', 'ts']
// 权限与标签:替换前。
function canAccess(role: string, allowed: string[]): boolean {
for (const r of allowed) {
if (r === role) return true;
}
return false;
}
function uniqueTags(tags: string[]): string[] {
const result: string[] = [];
for (const t of tags) if (!result.includes(t)) result.push(t);
return result;
}
console.log(canAccess("editor", ["admin", "editor"]), JSON.stringify(uniqueTags(["py", "ts", "py"])));
// 输出:
// true ["py","ts"]
"""权限与标签:替换后。"""
def can_access(role: str, allowed: list[str]) -> bool:
return role in allowed
def unique_tags(tags: list[str]) -> list[str]:
return list(dict.fromkeys(tags))
if __name__ == "__main__":
print(can_access("editor", ["admin", "editor"]), unique_tags(["py", "ts", "py"]))
# 输出:
# True ['py', 'ts']
// 权限与标签:替换后。
function canAccess(role: string, allowed: string[]): boolean {
return allowed.includes(role);
}
function uniqueTags(tags: string[]): string[] {
return [...new Set(tags)];
}
console.log(canAccess("editor", ["admin", "editor"]), JSON.stringify(uniqueTags(["py", "ts", "py"])));
// 输出:
// true ["py","ts"]

in 和 includes 一个词说清了“在不在名单里”。去重用的 dict.fromkeys 和 Set 都保留第一次出现的顺序,行为和手写循环一致;直接用 Python 的 set() 会打乱顺序,那就不是重构了。

以函数调用取代内联代码:用一个已有函数的调用替换一段做同样事情的代码。它和提炼函数的区别在于函数已经存在,常常是标准库函数。熟悉标准库是做这个手法的前提:any、all、sum、max(key=...)、sorted、collections.Counter、itertools.groupby,以及 JS 的 some、every、find、Object.entries、Array.from。替换前确认边界行为一致:空列表、重复元素、顺序、None 和 undefined。

标准库函数的语义和手写代码在边界上不一样时,替换会悄悄改变行为,比如去重时顺序变了、max 遇到空列表抛错而原来返回默认值。这时要么选对函数(max(xs, default=0)),要么保留手写代码。