Skip to content

Commit

Permalink
更新 重构
Browse files Browse the repository at this point in the history
  • Loading branch information
0xcaffebabe committed Jul 2, 2020
1 parent e5522ed commit 9a1264f
Show file tree
Hide file tree
Showing 2 changed files with 171 additions and 1 deletion.
Binary file added assets/批注 2020-07-02 124318.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
172 changes: 171 additions & 1 deletion 软件工程/编码/代码重构.md
Expand Up @@ -384,4 +384,174 @@ function foundPerson(people) {
 const candidates = ["Don", "John", "Kent"];
 return people.find(p => candidates.includes(p)) || '';
}
```
```

### 搬移特性

- 搬移函数

对于某函数,如果它频繁使用了其他上下文的元素,那么就考虑将它搬移到那个上下文里

```js
class Account {
 get overdraftCharge() {...}
}
```


```js
class AccountType {
get overdraftCharge() {...}
}
```

- 搬移字段

![批注 2020-07-02 124318](/assets/批注%202020-07-02%20124318.png)

对于早期设计不良的数据结构,使用此方法改造它

```js
class Customer {
get plan() {return this._plan;}
get discountRate() {return this._discountRate;}
}
```


```js
class Customer {
get plan() {return this._plan;}
get discountRate() {return this.plan.discountRate;}
}
```

- 搬移语句到函数

使用这个方法将分散的逻辑聚合到函数里面,方便理解修改

```js
result.push(`<p>title: ${person.photo.title}</p>`);
result.concat(photoData(person.photo));

function photoData(aPhoto) {
 return [
  `<p>location: ${aPhoto.location}</p>`,
  `<p>date: ${aPhoto.date.toDateString()}</p>`,
];
}
```


```js
result.concat(photoData(person.photo));

function photoData(aPhoto) {
 return [
  `<p>title: ${aPhoto.title}</p>`,
  `<p>location: ${aPhoto.location}</p>`,
  `<p>date: ${aPhoto.date.toDateString()}</p>`,
 ];
}
```

- 搬移语句到调用者

上述的反向操作

对于代码演进,函数某些代码职责发生变化,将它们移除出去

- 以函数调用取代内联代码

一些函数的函数名就拥有足够的表达能力

```js
let appliesToMass = false;
for(const s of states) {
if (s === "MA") appliesToMass = true;
}
```


```js
appliesToMass = states.includes("MA");
```

- 移动语句

让存在关联的东西一起出现,可以使代码更容易理解

```js
const pricingPlan = retrievePricingPlan();
const order = retreiveOrder();
let charge;
const chargePerUnit = pricingPlan.unit;
```


```js
const pricingPlan = retrievePricingPlan();
const chargePerUnit = pricingPlan.unit;
const order = retreiveOrder();
let charge;
```

- 拆分循环

对一个循环做了多件事的代码,拆分它,使各段代码职责更加明确

虽然这样可能会对性能造成一些损失

```js
let averageAge = 0;
let totalSalary = 0;
for (const p of people) {
 averageAge += p.age;
 totalSalary += p.salary;
}
averageAge = averageAge / people.length;
```


```js
let totalSalary = 0;
for (const p of people) {
 totalSalary += p.salary;
}

let averageAge = 0;
for (const p of people) {
 averageAge += p.age;
}
averageAge = averageAge / people.length;
```

- 以管代取代循环

一些逻辑如果采用管道编写,可读性会更强

```js
const names = [];
for (const i of input) {
if (i.job === "programmer")
names.push(i.name);
}
```


```js
const names = input
.filter(i => i.job === "programmer")
.map(i => i.name);
```

- 移除死代码

移除那些永远不会允许的代码

0 comments on commit 9a1264f

Please sign in to comment.