visit
Favor immutability by converting attributes to sets
TL;DR: Using sets for attributes simplifies your code and makes state management easier
//gzht888.com/how-to-find-the-stinky-parts-of-your-code-part-vii-8dk31x0
//gzht888.com/how-to-find-the-stinky-parts-of-your-code-part-vi-cmj31om
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();
manager.addBill(bill);
console.log(accountant.unpaidBills.has(bill)); // true
manager.payBill(bill);
console.log(accountant.paidBills.has(bill)); // true
Without Proper Instructions | With Specific Instructions |
---|---|