# 代码重构 “如果尿布臭了,就换掉它。”-语出 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`,执行单元测试,通过: ![image-20210322143937732](https://img.kancloud.cn/b5/2d/b52d10f27c6a3b05328e16f526843bfc_684x138.png) 实体类有了,下一步我们将实体类应该到对应的组件中: ```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`,则编辑器会实时地报告一个错误: ![image-20210322144256987](https://img.kancloud.cn/31/7a/317a8a145191578bb1cda0c512fec2be_2580x286.png) ### 重构/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) |