# 代碼重構
“如果尿布臭了,就換掉它。”-語出 Beck 奶奶,論撫養小孩的哲學。重構,絕對是軟件開發寫程序過程中最重要的事之一。沒有重構的項目隨著時間的推移必然會成為老太太的裹腳布 ---- 又臭又長。
下面,我們按以下幾步對當前項目進行重構,以使得整個項目看起來更易懂,修改其來更容易。
## 建立實體類
建立實體類(接口)將后臺API交互過程中對返回的數據進行了規范。這種規范使得團隊成員再與后臺交互時完全的規避拼寫錯誤,即使錯了,整個項目對某個字段的修改也僅僅需要一次。
> 實體類:由于該類的作用是對應后臺返回的**實體entity**,所以我們把這種類稱為實體類。
本節在新建班級時,并沒有創建對應的班級實體類,實雖然并不影響當前功能實現,但明顯**班級實體**日后還需要在**班級列表**,**班級編輯**中被再次使用。我們來到src/app/entity文件夾,然后執行`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`實體類中增加`id`,`name`,`teacher`屬性:
```typescript
import {Teacher} from './teacher';
export class Clazz {
id: number;
name: string;
teacher: Teacher;
}
```
然后如下初始化構造函數:
```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 = {}`來初始化一個帶有默認值的參數。
- ② 使用as來進行轉換,規定參數的類型
- ③ ? 號的作用是指該屬性可有可無。
- ④ 由于③的存在,`data.id`的值可能是`undefined`,這里使用`as number`防止報類型不匹配的錯誤。
哪此一來,我們便可以使用如下語句來實例化`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`,執行單元測試,通過:

實體類有了,下一步我們將實體類應該到對應的組件中:
```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
});
```
此時如果我們不小心把`name`拼寫為`naem`,則編輯器會實時地報告一個錯誤:

### 重構/src/app/entity/teacher.ts
既然如上的構造函數這么優秀,我們打開`/src/app/entity/teacher.ts`,按上述方法重寫一便構造函數:
```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這個強類型的語言,能夠快速發現在重構過程中發生的問題。上述構造函數重構后,在啟用`ng t`的控制臺將得到如下錯誤提醒:
```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();
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
```
打開相應的錯誤文件,修正如下:
```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();
});
});
```
新的構造函數有了,歷史上一些不太好的寫法終于可心退出舞臺了:
```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>();
```
## 剝離測試類
在進行MockApi的過程中,我們在`clazz/add/add.component.mock-api.spec.ts`建立了兩個模擬API用的內部類`ClazzMockApi`、 `TeacherMockApi`,其它成員不會關注到此內部類的存在,同時將模擬班級與模擬教師放在一起,也不利于管理。
為此,我們在src/app下新建mock-api文件夾,然后將兩個內部類移動過去:
```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內容如下:
```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('接收到了數據請求,請求主體的內容為:', options.body);
const clazz = options.body;
if (!clazz.name || clazz.name === '') {
throw new Error('班級名稱未定義或為空');
}
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`關鍵字 ?? 。
teacher.mock.api.ts內容如下:
```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`重構:
```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 {
-請將本行及以下代碼全部刪除,限于篇幅,略過.
```
好了,終于不那么過分的不合格了,就到這里。
## 本節作業
項目中仍然存在待重構的`Teacher`,請嘗試找到它們并完成重構。
| 名稱 | 地址 |
| ---------------- | ------------------------------------------------------------ |
| TypeScript模塊 | [https://www.tslang.cn/docs/handbook/modules.html](https://www.tslang.cn/docs/handbook/modules.html) |
| 本節源碼(含答案) | [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 環境安裝
- 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 請求后臺數據
- 2.2.1 HttpClient
- 2.2.2 請求數據
- 2.2.3 模塊與依賴注入
- 2.2.4 異步與回調函數
- 2.2.5 集成測試
- 2.2.6 本章小節
- 2.3 新增教師
- 2.3.1 組件初始化
- 2.3.2 [(ngModel)]
- 2.3.3 對接后臺
- 2.3.4 路由
- 2.4 編輯教師
- 2.4.1 組件初始化
- 2.4.2 獲取路由參數
- 2.4.3 插值與模板表達式
- 2.4.4 初識泛型
- 2.4.5 更新教師
- 2.4.6 測試中的路由
- 2.5 刪除教師
- 2.6 收尾工作
- 2.6.1 RouterLink
- 2.6.2 fontawesome圖標庫
- 2.6.3 firefox
- 2.7 總結
- 第三章 用戶登錄
- 3.1 初識單元測試
- 3.2 http概述
- 3.3 Basic access authentication
- 3.4 著陸組件
- 3.5 @Output
- 3.6 TypeScript 類
- 3.7 瀏覽器緩存
- 3.8 總結
- 第四章 個人中心
- 4.1 原型
- 4.2 管道
- 4.3 對接后臺
- 4.4 x-auth-token認證
- 4.5 攔截器
- 4.6 小結
- 第五章 系統菜單
- 5.1 延遲及測試
- 5.2 手動創建組件
- 5.3 隱藏測試信息
- 5.4 規劃路由
- 5.5 定義菜單
- 5.6 注銷
- 5.7 小結
- 第六章 班級管理
- 6.1 新增班級
- 6.1.1 組件初始化
- 6.1.2 MockApi 新建班級
- 6.1.3 ApiInterceptor
- 6.1.4 數據驗證
- 6.1.5 教師選擇列表
- 6.1.6 MockApi 教師列表
- 6.1.7 代碼重構
- 6.1.8 小結
- 6.2 教師列表組件
- 6.2.1 初始化
- 6.2.2 響應式表單
- 6.2.3 getTestScheduler()
- 6.2.4 應用組件
- 6.2.5 小結
- 6.3 班級列表
- 6.3.1 原型設計
- 6.3.2 初始化分頁
- 6.3.3 MockApi
- 6.3.4 靜態分頁
- 6.3.5 動態分頁
- 6.3.6 @Input()
- 6.4 編輯班級
- 6.4.1 測試模塊
- 6.4.2 響應式表單驗證
- 6.4.3 @Input()
- 6.4.4 FormGroup
- 6.4.5 自定義FormControl
- 6.4.6 代碼重構
- 6.4.7 小結
- 6.5 刪除班級
- 6.6 集成測試
- 6.6.1 惰性加載
- 6.6.2 API攔截器
- 6.6.3 路由與跳轉
- 6.6.4 ngStyle
- 6.7 初識Service
- 6.7.1 catchError
- 6.7.2 單例服務
- 6.7.3 單元測試
- 6.8 小結
- 第七章 學生管理
- 7.1 班級列表組件
- 7.2 新增學生
- 7.2.1 exports
- 7.2.2 自定義驗證器
- 7.2.3 異步驗證器
- 7.2.4 再識DI
- 7.2.5 屬性型指令
- 7.2.6 完成功能
- 7.2.7 小結
- 7.3 單元測試進階
- 7.4 學生列表
- 7.4.1 JSON對象與對象
- 7.4.2 單元測試
- 7.4.3 分頁模塊
- 7.4.4 子組件測試
- 7.4.5 重構分頁
- 7.5 刪除學生
- 7.5.1 第三方dialog
- 7.5.2 批量刪除
- 7.5.3 面向對象
- 7.6 集成測試
- 7.7 編輯學生
- 7.7.1 初始化
- 7.7.2 自定義provider
- 7.7.3 更新學生
- 7.7.4 集成測試
- 7.7.5 可訂閱的路由參數
- 7.7.6 小結
- 7.8 總結
- 第八章 其它
- 8.1 打包構建
- 8.2 發布部署
- 第九章 總結