转换静态函数
TL;DR:用对象交互代替静态函数。
解决的问题
相关代码异味
代码异味 18 — 静态函数 Maxi Contieri ・ 20 年 11 月 6 日 #codenewbie #tutorial #development #coding代码异味 17 - 全局函数 Maxi Contieri ・ 20 年 11 月 5 日 #codenewbie #development #tutorial代码异味 22 - 助手 Maxi Contieri ・ 20 年 11 月 12 日 #oop #helpers #codenewbie #beginners步骤
示例代码
前
class CharacterUtils {
static createOrpheus() {
return { name: "Orpheus", role: "Musician" };
}
static createEurydice() {
return { name: "Eurydice", role: "Wanderer" };
}
static lookBack(character) {
if (character.name === "Orpheus") {
return "Orpheus looks back and loses Eurydice.";
} else if (character.name === "Eurydice") {
return "Eurydice follows Orpheus in silence.";
}
return "Unknown character.";
}
}
const orpheus = CharacterUtils.createOrpheus();
const eurydice = CharacterUtils.createEurydice();后
// 1. Identify static methods used in your code.
// 2. Replace static methods with instance methods.
// 3. Pass dependencies explicitly through
// constructors or method parameters.
class Character {
constructor(name, role, lookBackBehavior) {
this.name = name;
this.role = role;
this.lookBackBehavior = lookBackBehavior;
}
lookBack() {
return this.lookBackBehavior(this);
}
}
// 4. Refactor clients to interact with objects
// instead of static functions.
const orpheusLookBack = (character) =>
"Orpheus looks back and loses Eurydice.";
const eurydiceLookBack = (character) =>
"Eurydice follows Orpheus in silence.";
const orpheus = new Character("Orpheus", "Musician", orpheusLookBack);
const eurydice = new Character("Eurydice", "Wanderer", eurydiceLookBack);类型
[X] 半自动
您可以逐步进行替换。
安全
这种重构通常是安全的,但您应该彻底测试您的更改。
确保代码的其他部分不依赖于您替换的静态方法。
为什么该代码更好?
您的代码更易于测试,因为您可以在测试期间替换依赖项。
对象封装行为,提高内聚力并减少协议过载。
您可以删除隐藏的全局依赖关系,使代码更清晰,更易于理解。
使用 AI 进行重构
ChatGPTChatGPT克劳德克劳德困惑困惑副驾驶副驾驶双子座双子座标签
相关重构
参见
耦合:唯一的软件设计问题 Maxi Contieri ・ 2 月 6 日 '21 #webdev #programming #oop #tutorial致谢
该图片由Menno van der Krift在Pixabay上发布
本文是重构系列的一部分。
如何通过简单的重构改进代码 Maxi Contieri ・ 22 年 10 月 24 日 #webdev #beginners #programming #tutorial