数据结构与算法之美(三)
数据结构与算法之美(二)
数据结构与算法之美(一)
labuladong的算法小抄(一)
LeedCode 摩尔投票
重构-改善既有代码的设计(七)
重构-改善既有代码的设计(六)
重构API
将查询函数和修改函数分离(Separate Query from Modifier)
示例
1
2
3
4
5function getTotalOutatandingAndSendBill(){
const result = customer.invoices.reduce((total, each) => each.amount + total, 0);
sendBill();
return result;
}重构为
1
2
3
4
5
6function totalOutstanding(){
return customer.invoices.reduce((total, each) => each.amount + total, 0);
}
function sendBill(){
emailGateway.send(formatBill(customer));
}
重构-改善既有代码的设计(五)
重构-改善既有代码的设计(四)
重构-改善既有代码的设计(三)
封装
封装记录(Encapsulate Record)
示例
1
organization = {name: "Acme Gooseberries",country:"GB"};
重构为
1
2
3
4
5
6
7
8
9
10class Oraganization{
constructor(data){
this._name = data.name;
this._country = data.country;
}
get name() { return this._name; }
set name(arg) {this._name = arg; }
get country() { return this._country; }
set country(arg) {this._country = arg; }
}
重构-改善既有代码的设计(二)
重构名录-第一组重构
提炼函数(Extract Function)
示例
1
2
3
4
5
6
7
8function printOwing(invoice){
printBanner()
let outstanding = calculateOutstanding();
// print details
console.log(`name:${invoice.customer}`);
console.log(`amount:${outstanding}`);
}重构为
1
2
3
4
5
6
7
8
9
10function printOwing(invoice){
printBanner()
let outstanding = calculateOutstanding();
printDetails(outstanding)
function printDetails(outstanding){
console.log(`name:${invoice.customer}`);
console.log(`amount:${outstanding}`);
}
}
