# 代碼重構(gòu)
“如果尿布臭了,就換掉它。”-語出 Beck 奶奶,論撫養(yǎng)小孩的哲學(xué)。重構(gòu),絕對是軟件開發(fā)寫程序過程中最重要的事之一。沒有重構(gòu)的項(xiàng)目隨著時(shí)間的推移必然會成為老太太的裹腳布 ---- 又臭又長。
下面,我們按以下幾步對當(dāng)前項(xiàng)目進(jìn)行重構(gòu),以使得整個(gè)項(xiàng)目看起來更易懂,修改其來更容易。
## 建立實(shí)體類
建立實(shí)體類(接口)將后臺API交互過程中對返回的數(shù)據(jù)進(jìn)行了規(guī)范。這種規(guī)范使得團(tuán)隊(duì)成員再與后臺交互時(shí)完全的規(guī)避拼寫錯(cuò)誤,即使錯(cuò)了,整個(gè)項(xiàng)目對某個(gè)字段的修改也僅僅需要一次。
> 實(shí)體類:由于該類的作用是對應(yīng)后臺返回的**實(shí)體entity**,所以我們把這種類稱為實(shí)體類。
本節(jié)在新建班級時(shí),并沒有創(chuàng)建對應(yīng)的班級實(shí)體類,實(shí)雖然并不影響當(dāng)前功能實(shí)現(xiàn),但明顯**班級實(shí)體**日后還需要在**班級列表**,**班級編輯**中被再次使用。我們來到src/app/entity文件夾,然后執(zhí)行`ng g class Clazz`命令來生成一新類:
```bash
panjie@panjies-Mac-Pro entity % ng g class clazz
CREATE src/app/entity/clazz.spec.ts (150 bytes)
CREATE src/app/entity/clazz.ts (23 bytes)
```
然后在`clazz`實(shí)體類中增加`id`,`name`,`teacher`屬性:
```typescript
import {Teacher} from './teacher';
export class Clazz {
id: number;
name: string;
teacher: Teacher;
}
```
然后如下初始化構(gòu)造函數(shù):
```typescript
constructor(data = {} ① as ② {
id?③: number;
name?③: string;
teacher?③: Teacher;
}) {
this.id = data.id as number; ④
this.name = data.name as string;
this.teacher = data.teacher as Teacher;
}
```
- ① 使用`data = {}`來初始化一個(gè)帶有默認(rèn)值的參數(shù)。
- ② 使用as來進(jìn)行轉(zhuǎn)換,規(guī)定參數(shù)的類型
- ③ ? 號的作用是指該屬性可有可無。
- ④ 由于③的存在,`data.id`的值可能是`undefined`,這里使用`as number`防止報(bào)類型不匹配的錯(cuò)誤。
哪此一來,我們便可以使用如下語句來實(shí)例化`Clazz`了:
```typescript
+++ b/first-app/src/app/entity/clazz.spec.ts
@@ -1,10 +1,12 @@
import {Clazz} from './clazz';
+import {Teacher} from './teacher';
describe('Clazz', () => {
it('should create an instance', () => {
expect(new Clazz()).toBeTruthy();
expect(new Clazz({id: 123})).toBeTruthy();
- expect(new Clazz()).toBeTruthy();
- expect(new Clazz()).toBeTruthy();
+ expect(new Clazz({name: 'test'})).toBeTruthy();
+ expect(new Clazz({teacher: {id: 1} as Teacher})).toBeTruthy();
+ expect(new Clazz({id: 123, name: 'test', teacher: {id: 1} as Teacher})).toBeTruthy();
});
});
```
將`it`變更為`fit`,執(zhí)行單元測試,通過:

實(shí)體類有了,下一步我們將實(shí)體類應(yīng)該到對應(yīng)的組件中:
```typescript
+++ b/first-app/src/app/clazz/add/add.component.ts
+import {Clazz} from '../../entity/clazz';
onSubmit(): void {
const newClazz = new Clazz({
name: this.clazz.name,
teacher: {
id: this.clazz.teacherId
} as Teacher
});
```
此時(shí)如果我們不小心把`name`拼寫為`naem`,則編輯器會實(shí)時(shí)地報(bào)告一個(gè)錯(cuò)誤:

### 重構(gòu)/src/app/entity/teacher.ts
既然如上的構(gòu)造函數(shù)這么優(yōu)秀,我們打開`/src/app/entity/teacher.ts`,按上述方法重寫一便構(gòu)造函數(shù):
```typescript
+++ b/first-app/src/app/entity/teacher.ts
@@ -9,12 +9,13 @@ export class Teacher {
sex: boolean;
username: string;
- constructor(id: number, email: string, name: string, password: string, sex: boolean, username: string) {
- this.id = id;
- this.email = email;
- this.name = name;
- this.password = password;
- this.sex = sex;
- this.username = username;
+ constructor(data = {} as {
+ id?: number, email?: string, name?: string, password?: string, sex?: boolean, username?: string}) {
+ this.id = data.id as number;
+ this.email = data.email as string;
+ this.name = data.name as string;
+ this.password = data.password as string;
+ this.sex = data.sex as boolean;
+ this.username = data.username as string;
}
}
```
typescript這個(gè)強(qiáng)類型的語言,能夠快速發(fā)現(xiàn)在重構(gòu)過程中發(fā)生的問題。上述構(gòu)造函數(shù)重構(gòu)后,在啟用`ng t`的控制臺將得到如下錯(cuò)誤提醒:
```bash
Error: src/app/entity/teacher.spec.ts:5:27 - error TS2554: Expected 0-1 arguments, but got 6.
5 expect(new Teacher(1, 'email', 'name', 'password', true, 'username')).toBeTruthy();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
打開相應(yīng)的錯(cuò)誤文件,修正如下:
```typescript
+++ b/first-app/src/app/entity/teacher.spec.ts
@@ -1,7 +1,14 @@
-import { Teacher } from './teacher';
+import {Teacher} from './teacher';
describe('Teacher', () => {
it('should create an instance', () => {
- expect(new Teacher(1, 'email', 'name', 'password', true, 'username')).toBeTruthy();
+ expect(new Teacher({
+ id: 1,
+ email: 'email',
+ name: 'name',
+ password: 'password',
+ sex: true,
+ username: 'username'
+ })).toBeTruthy();
});
});
```
新的構(gòu)造函數(shù)有了,歷史上一些不太好的寫法終于可心退出舞臺了:
```typescript
+++ b/first-app/src/app/clazz/add/add.component.ts
@@ -29,9 +29,7 @@ export class AddComponent implements OnInit {
onSubmit(): void {
const newClazz = new Clazz({
name: this.clazz.name,
- teacher: {
- id: this.clazz.teacherId
- } as Teacher
+ teacher: new Teacher({id: this.clazz.teacherId})
});
this.httpClient.post(this.url, newClazz)
.subscribe(clazz => console.log('保存成功', clazz),
```
```typescript
+++ b/first-app/src/app/login/login.component.ts
@@ -8,7 +8,7 @@ import {Teacher} from '../entity/teacher';
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
- teacher = {} as Teacher;
+ teacher = new Teacher();
@Output()
beLogin = new EventEmitter<Teacher>();
```
## 剝離測試類
在進(jìn)行MockApi的過程中,我們在`clazz/add/add.component.mock-api.spec.ts`建立了兩個(gè)模擬API用的內(nèi)部類`ClazzMockApi`、 `TeacherMockApi`,其它成員不會關(guān)注到此內(nèi)部類的存在,同時(shí)將模擬班級與模擬教師放在一起,也不利于管理。
為此,我們在src/app下新建mock-api文件夾,然后將兩個(gè)內(nèi)部類移動過去:
```bash
panjie@panjies-Mac-Pro app % pwd
/Users/panjie/github/mengyunzhi/angular11-guild/first-app/src/app
panjie@panjies-Mac-Pro app % tree mock-api
mock-api
├── clazz.mock.api.ts
└── teacher.mock.api.ts
0 directories, 2 files
```
clazz.mock.api.ts內(nèi)容如下:
```typescript
import {ApiInjector, MockApiInterface, randomNumber, RequestOptions} from '@yunzhi/ng-mock-api';
/**
* 班級模擬API
*/
export ?? class ClazzMockApi implements MockApiInterface {
getInjectors(): ApiInjector<any>[] {
return [
{
method: 'POST',
url: 'clazz',
result: (urlMatches: string[], options: RequestOptions) => {
console.log('接收到了數(shù)據(jù)請求,請求主體的內(nèi)容為:', options.body);
const clazz = options.body;
if (!clazz.name || clazz.name === '') {
throw new Error('班級名稱未定義或?yàn)榭?#039;);
}
if (!clazz.teacher || !clazz.teacher.id) {
throw new Error('班主任ID未定義');
}
return {
id: randomNumber(),
name: '保存的班級名稱',
createTime: new Date().getTime(),
teacher: {
id: clazz.teacher.id,
name: '教師姓名'
}
};
}
}
];
}
}
```
該類需要被本文件以外的文件`import`,所以必須使用`export`關(guān)鍵字 ?? 。
teacher.mock.api.ts內(nèi)容如下:
```typescript
import {ApiInjector, MockApiInterface, randomNumber} from '@yunzhi/ng-mock-api';
/**
* 教師模擬API
*/
export ?? class TeacherMockApi implements MockApiInterface {
getInjectors(): ApiInjector<any>[] {
return [{
// 獲取所有教師
method: 'GET',
url: 'teacher',
result: [
{
id: randomNumber(),
name: '教師姓名1'
},
{
id: randomNumber(),
name: '教師姓名2'
}
]
}];
}
}
```
最后對原`clazz/add/add.component.mock-api.spec.ts`重構(gòu):
```typescript
+++ b/first-app/src/app/clazz/add/add.component.mock-api.spec.ts
@@ -3,6 +3,8 @@ import {ComponentFixture, TestBed} from '@angular/core/testing';
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import {ApiInjector, MockApiInterceptor, MockApiInterface, randomNumber, RequestOptions} from '@yunzhi/ng-mock-api';
import {FormsModule} from '@angular/forms';
+import {ClazzMockApi} from '../../mock-api/clazz.mock.api';
+import {TeacherMockApi} from '../../mock-api/teacher.mock.api';
describe('clazz add with mockapi', () => {
let component: AddComponent;
@@ -38,61 +40,3 @@ describe('clazz add with mockapi', () => {
fixture.autoDetectChanges();
});
});
-
-/**
- * 班級模擬API
- */
-class ClazzMockApi implements MockApiInterface {
-請將本行及以下代碼全部刪除,限于篇幅,略過.
```
好了,終于不那么過分的不合格了,就到這里。
## 本節(jié)作業(yè)
項(xiàng)目中仍然存在待重構(gòu)的`Teacher`,請嘗試找到它們并完成重構(gòu)。
| 名稱 | 地址 |
| ---------------- | ------------------------------------------------------------ |
| TypeScript模塊 | [https://www.tslang.cn/docs/handbook/modules.html](https://www.tslang.cn/docs/handbook/modules.html) |
| 本節(jié)源碼(含答案) | [https://github.com/mengyunzhi/angular11-guild/archive/step6.1.7.zip](https://github.com/mengyunzhi/angular11-guild/archive/step6.1.7.zip) |
- 序言
- 第一章 Hello World
- 1.1 環(huán)境安裝
- 1.2 Hello Angular
- 1.3 Hello World!
- 第二章 教師管理
- 2.1 教師列表
- 2.1.1 初始化原型
- 2.1.2 組件生命周期之初始化
- 2.1.3 ngFor
- 2.1.4 ngIf、ngTemplate
- 2.1.5 引用 Bootstrap
- 2.2 請求后臺數(shù)據(jù)
- 2.2.1 HttpClient
- 2.2.2 請求數(shù)據(jù)
- 2.2.3 模塊與依賴注入
- 2.2.4 異步與回調(diào)函數(shù)
- 2.2.5 集成測試
- 2.2.6 本章小節(jié)
- 2.3 新增教師
- 2.3.1 組件初始化
- 2.3.2 [(ngModel)]
- 2.3.3 對接后臺
- 2.3.4 路由
- 2.4 編輯教師
- 2.4.1 組件初始化
- 2.4.2 獲取路由參數(shù)
- 2.4.3 插值與模板表達(dá)式
- 2.4.4 初識泛型
- 2.4.5 更新教師
- 2.4.6 測試中的路由
- 2.5 刪除教師
- 2.6 收尾工作
- 2.6.1 RouterLink
- 2.6.2 fontawesome圖標(biāo)庫
- 2.6.3 firefox
- 2.7 總結(jié)
- 第三章 用戶登錄
- 3.1 初識單元測試
- 3.2 http概述
- 3.3 Basic access authentication
- 3.4 著陸組件
- 3.5 @Output
- 3.6 TypeScript 類
- 3.7 瀏覽器緩存
- 3.8 總結(jié)
- 第四章 個(gè)人中心
- 4.1 原型
- 4.2 管道
- 4.3 對接后臺
- 4.4 x-auth-token認(rèn)證
- 4.5 攔截器
- 4.6 小結(jié)
- 第五章 系統(tǒng)菜單
- 5.1 延遲及測試
- 5.2 手動創(chuàng)建組件
- 5.3 隱藏測試信息
- 5.4 規(guī)劃路由
- 5.5 定義菜單
- 5.6 注銷
- 5.7 小結(jié)
- 第六章 班級管理
- 6.1 新增班級
- 6.1.1 組件初始化
- 6.1.2 MockApi 新建班級
- 6.1.3 ApiInterceptor
- 6.1.4 數(shù)據(jù)驗(yàn)證
- 6.1.5 教師選擇列表
- 6.1.6 MockApi 教師列表
- 6.1.7 代碼重構(gòu)
- 6.1.8 小結(jié)
- 6.2 教師列表組件
- 6.2.1 初始化
- 6.2.2 響應(yīng)式表單
- 6.2.3 getTestScheduler()
- 6.2.4 應(yīng)用組件
- 6.2.5 小結(jié)
- 6.3 班級列表
- 6.3.1 原型設(shè)計(jì)
- 6.3.2 初始化分頁
- 6.3.3 MockApi
- 6.3.4 靜態(tài)分頁
- 6.3.5 動態(tài)分頁
- 6.3.6 @Input()
- 6.4 編輯班級
- 6.4.1 測試模塊
- 6.4.2 響應(yīng)式表單驗(yàn)證
- 6.4.3 @Input()
- 6.4.4 FormGroup
- 6.4.5 自定義FormControl
- 6.4.6 代碼重構(gòu)
- 6.4.7 小結(jié)
- 6.5 刪除班級
- 6.6 集成測試
- 6.6.1 惰性加載
- 6.6.2 API攔截器
- 6.6.3 路由與跳轉(zhuǎn)
- 6.6.4 ngStyle
- 6.7 初識Service
- 6.7.1 catchError
- 6.7.2 單例服務(wù)
- 6.7.3 單元測試
- 6.8 小結(jié)
- 第七章 學(xué)生管理
- 7.1 班級列表組件
- 7.2 新增學(xué)生
- 7.2.1 exports
- 7.2.2 自定義驗(yàn)證器
- 7.2.3 異步驗(yàn)證器
- 7.2.4 再識DI
- 7.2.5 屬性型指令
- 7.2.6 完成功能
- 7.2.7 小結(jié)
- 7.3 單元測試進(jìn)階
- 7.4 學(xué)生列表
- 7.4.1 JSON對象與對象
- 7.4.2 單元測試
- 7.4.3 分頁模塊
- 7.4.4 子組件測試
- 7.4.5 重構(gòu)分頁
- 7.5 刪除學(xué)生
- 7.5.1 第三方dialog
- 7.5.2 批量刪除
- 7.5.3 面向?qū)ο?/a>
- 7.6 集成測試
- 7.7 編輯學(xué)生
- 7.7.1 初始化
- 7.7.2 自定義provider
- 7.7.3 更新學(xué)生
- 7.7.4 集成測試
- 7.7.5 可訂閱的路由參數(shù)
- 7.7.6 小結(jié)
- 7.8 總結(jié)
- 第八章 其它
- 8.1 打包構(gòu)建
- 8.2 發(fā)布部署
- 第九章 總結(jié)