首页  >  文章  >  web前端  >  重构 - 将属性转换为集合

重构 - 将属性转换为集合

Barbara Streisand
Barbara Streisand原创
2024-10-20 11:33:02614浏览

通过将属性转换为集合来支持不变性

TL;DR:使用属性集可以简化代码并使状态管理更容易

解决的问题

  • 可变性
  • 复杂性
  • 属性被污染
  • 设置器

相关代码异味

步骤

  1. 识别代表状态的属性
  2. 用集合替换属性:每个状态一个
  3. 调整在集合之间移动项目的方法,而不是改变属性

示例代码

class Bill {
  amount: number;
  paid: boolean;

  constructor(amount: number) {
    this.amount = amount;
    this.paid = false;
  }

  pay() {
    if (!this.paid) {
      this.paid = true;
    }
  }
}

const bill = new Bill(100);
console.log(bill.paid); // false
bill.pay();
console.log(bill.paid); // true

// 1. Identify attributes representing states

class Accountant {  
   // 2. Replace the attributes with sets: one for each state
  unpaidBills: Set<Bill>;
  paidBills: Set<Bill>;

  constructor() {
    this.unpaidBills = new Set();
    this.paidBills = new Set();
  }

  addBill(bill: Bill) {
    this.unpaidBills.add(bill);
  }

  payBill(bill: Bill) {    
    // 3. Adjust methods to move items
    // between sets instead of mutating attributes
    if (this.unpaidBills.has(bill)) {
      this.unpaidBills.delete(bill);
      this.paidBills.add(bill);
    }
  }
}

class Bill {
  amount: number;

  constructor(amount: number) {
    this.amount = amount;
  }
}

const bill = new Bill(100);
const accountant = new Accountant();
accountant.addBill(bill);
console.log(accountant.unpaidBills.has(bill)); // true
accountant.payBill(bill);
console.log(accountant.paidBills.has(bill)); // true

类型

[X] 半自动

安全

当您的属性不依赖于特定的索引行为时,此重构是安全的。

由于集合不维护元素顺序,请检查您的逻辑是否依赖于顺序。

为什么代码更好?

实体本质上是不可变的。

使用集合可确保唯一性并简化逻辑。

添加元素之前不再需要检查重复项。

并集、交集和差集等操作变得简单,使您的代码更易于维护和灵活。

局限性

集合不保留元素顺序。

如果您的逻辑依赖于顺序,则转换为集合可能不合适,您应该使用有序集合或数组

人工智能重构

您可以提示您的 AI 助手为您进行此重构。

尝试一下!

Without Proper Instructions With Specific Instructions
ChatGPT ChatGPT
Claude Claude
Perplexity Perplexity
Copilot Copilot
Gemini Gemini

标签

  • 可变性

相关重构

https://dev.to/mcsee/refactoring-001-remove-setters-26cg

参见

制作人员

图片由 Angelo Giordano 在 Pixabay上


本文是重构系列的一部分。

以上是重构 - 将属性转换为集合的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn