• TS代码整洁之道(上)


    TS代码整洁之道——"净"

    maxueming|2022-10


    干”净“的代码,有利于项目代码维护、升级和迭代。最近读了Robert C. Martin 的 《Clean  Code》一书,感触颇多,结合TS,聊聊TS的代码整洁之道——“净”

    可能因为我们一直关注需求和模型,代码往往被忽略。虽然现在有很多低代码平台可以批量生产代码,但是代码层面的抽象和其呈现的细节是无法被忽视的。

    我们可能都碰到过类的情况:项目初期迅速迭代,随着项目日渐复杂,维护迭代成本逐渐变大,对A处代码的修改都会影响C和D处代码,甚至你不知道会不会影响其他地方代码。随着混乱增加,团队的生产力下降,开发效率降低,开发成本回增高。

    为了解决以上因“糟糕”代码带来的各种问题,在读完《Clean Code》后总结一下代码整洁之道,核心围绕“净”。

    1.命名之道——"意净"

    计算机科学只存在两个难题:缓存失效和命名。——Phil KarIton

    在代码中,好的命名和艺术一般美妙,在大型项目中,由于项目参与人数多,迭代时间长,好的命名规则可以防止项目命名系统混乱,提高开发效率。

    变量名应该具备一下几个特性:

    意义性:可以根据变量的本身作用和含义给变量取一个有明确具体含义的变量名称。

    可读性:根据变量的意义和作用给变量起一个可以读的名称,方便沟通、理解、维护。

    搜索性:在大量的代码中,变量的可搜索性非常重要,将一些代码抽象并命名为变量,有利于他人开发,提升开发效率。

    自解释:取的变量名,可以自己解释自己本身的含义,让开发者一目了然,容易理解,避免使用无意义的名称。

    合并性:功能重复的情况下,要精简成一个,其余都是冗余代码。

    明确性:避免思维映射,不要让别人猜测或者想象你的变量含义。

    无用上下文:如果类型名已经表达了明确的信息,那么,内部变量名中不要再重复表达。

    默认参数:使用默认参数,而非短路或条件判断。

    1. //1.意义性
    2. const yyyymmdd = moment().format("YYYY/MM/DD");// bad
    3. const currentDate = moment().format("YYYY/MM/DD");//good
    4. //2.可读性
    5. class Usr123 { //bad
    6. private asdf = '123';
    7. // ...
    8. }
    9. class User { //good
    10. private id = '123';
    11. // ...
    12. }
    13. // 3.搜索性
    14. setTimeout(restart, 86400000); // bad 86400000 代表什么?它是魔数!
    15. const MILLISECONDS_IN_A_DAY = 24 * 60 * 60 * 1000;//good 声明为常量,要大写且有明确含义。
    16. setTimeout(restart, MILLISECONDS_IN_A_DAY);
    17. //4.自解释
    18. declare const users: Map<string, User>;
    19. for (const kv of users) { // bad kv是啥???
    20. // ...
    21. }
    22. declare const users: Map<string, User>;
    23. // 变量名解析自身的含义
    24. for (const [id, user] of users) {//good id 和user都有意义
    25. // ...
    26. }
    27. //5.合并性
    28. //bad
    29. function getUserInfo(): User;
    30. function getUserDetails(): User;
    31. function getUserData(): User;
    32. function getUser(): User;//good
    33. //6.明确性
    34. //bad
    35. const u = getUser();
    36. const s = getSubscription();
    37. const t = charge(u, s);
    38. //good
    39. const user = getUser();
    40. const subscription = getSubscription();
    41. const transaction = charge(user, subscription);
    42. //7.无用上下文
    43. //bad
    44. type User = {
    45. userId: string;
    46. userName: string;
    47. userAge: number;
    48. }
    49. //good
    50. type User = {
    51. id: string;
    52. name: string;
    53. age: string;
    54. }
    55. // 8.默认参数
    56. //bad
    57. function loadPages(count: number) {
    58. const loadCount = count !== undefined ? count : 10;
    59. // ...
    60. }
    61. //good
    62. function loadPages(count: number = 10) {
    63. // ...
    64. }

    推荐命名神器:

    对于我们国内程序员来说,取个有意义的变量名也着实考验英语基本功。可以尝试使用 CODELF 变量命名神器,在 VSCode、Sublime Text 都有插件。另外,对现有代码的命名进行重构,最好使用 IDE 自带的重构功能,避免出错。

     

    当然以上的变量命名规则是最基本的,在大型项目中,还需要我们根据项目本身的特点,设计具体的命名规范,来约束开发者,增强代码可维护性。

    2.函数之道——“干净”

    一个函数函数应该只干一件事,这就是函数体本身要干净,不能干其他琐碎的事,不利于开发者阅读与理解代码。

    少参数:一个函数,参数最多不超过3个,超过3个参数让函数功能变得复杂,应为函数的组合便多了。

    一般最多两个参数,如果超过两个参数,你可以考虑他否否和一件事原则吗?不符合,可以考虑继续拆分函数。

    但是在某些特殊情况下,确实需要多个参数,但是可以考虑使用对象,为了让函数定义更清晰,可以使用结构。结构传参有以下好处:1.便于查看函数签名;2.结构深拷贝,无副作用。3.TS校验未使用的属性。

    1. //bad
    2. function reqeust(method: string, url: string, body: string, headers: string) {
    3. // ...
    4. }
    5. reqeust('POST', '/api/service/v1/users', body, headers);
    6. //good
    7. function reqeust(method: string, url: string, body: string, headers: string) {
    8. // ...
    9. }
    10. reqeust(
    11. {
    12. method: 'POST',
    13. url: '/api/service/v1/users',
    14. body: body,
    15. headers: headers
    16. }
    17. );
    18. //也可以使用 TypeScript 的类型别名,进一步提高可读性。
    19. type RequestOptions = {method: string, url: string, body: string, headers: string};
    20. function request(options: RequestOptions) {
    21. // ...
    22. }
    23. reqeust(
    24. {
    25. method: 'POST',
    26. url: '/api/service/v1/users',
    27. body: body,
    28. headers: headers
    29. }
    30. );

    一件事:单一功能的函数,让代码更清晰,更容易理解。比如勿用Flag,Flag 参数则说明这个函数做了不止一件事。如果函数使用布尔值实现不同的代码逻辑路径,则考虑将其拆分。

    1. //bad
    2. function sendEmail(users: User) {
    3. users.forEach((user) => {
    4. const userRecord = database.lookup(user);
    5. if (userRecord.isActive()) {
    6. email(user);
    7. }
    8. });
    9. }
    10. //good
    11. function sendEmail(users: User) {
    12. users.filter(isActive).forEach(email);
    13. }
    14. function isActive(user: User) {
    15. return database.lookup(user).isActive();
    16. }

    名副其实:见其名,懂其能。

    1. //bad
    2. // 从函数名很难看清楚对日期做什么操作?加一天、一月?
    3. addToDate(date, 1);
    4. //good
    5. addMonthToDate(date, 1);

    单层级抽象:当有多个抽象级别时,函数应该是做太多事了

    1. //bad
    2. function parseCode(code: string) {
    3. const REGEXES = [ /* ... */ ];
    4. const statements = code.split(' ');
    5. const tokens = [];
    6. REGEXES.forEach((regex) => {
    7. statements.forEach((statement) => {
    8. // ...
    9. });
    10. });
    11. const ast = [];
    12. tokens.forEach((token) => {
    13. // 词法分析...
    14. });
    15. ast.forEach((node) => {
    16. // 解析 ...
    17. });
    18. }
    19. //good
    20. const REGEXES = [ /* ... */ ];
    21. function parseCode(code: string) {
    22. const tokens = tokenize(code);
    23. const syntaxTree = parse(tokens);
    24. syntaxTree.forEach((node) => {
    25. // 解析...
    26. });
    27. }
    28. function tokenize(code: string):Token[] {
    29. const statements = code.split(' ');
    30. const tokens:Token[] = [];
    31. REGEXES.forEach((regex) => {
    32. statements.forEach((statement) => {
    33. tokens.push( /* ... */ );
    34. });
    35. });
    36. return tokens;
    37. }
    38. function parse(tokens: Token[]): SyntaxTree {
    39. const syntaxTree:SyntaxTree[] = [];
    40. tokens.forEach((token) => {
    41. syntaxTree.push( /* ... */ );
    42. });
    43. return syntaxTree;
    44. }

    避免重复:重复万恶之源

    如果需要某一处重复的代码逻辑,你需要修改多处,很容易遗漏。一般是存在多个相似功能的模块,但又不同,造成的。

    使用抽象来解决,抽象成函数、模块或者类来处理这些不同的地方。注意遵循 SOLID 原则, 因为糟糕的抽象可能还不如重复代码。

    当然也要权引入不必要的抽象造成增加复杂性,去要开发者去权衡。当来自不同领域的两个不同模块,它们的实现看起来相似,复制也是可以接受的,并且比抽取公共代码要好一点。因为抽取公共代码会导致两个模块产生间接的依赖关系。

    1. //bad
    2. private showDeveloperList(developers: Developer[]) {
    3. developers.forEach((developer) => {
    4. const expectedSalary = developer.calculateExpectedSalary();
    5. const experience = developer.getExperience();
    6. const githubLink = developer.getGithubLink(); // 此处存在不同的地方,其余逻辑一样
    7. const data = {
    8. expectedSalary,
    9. experience,
    10. githubLink
    11. };
    12. render(data);
    13. });
    14. }
    15. private showManagerList(managers: Manager[]) {
    16. managers.forEach((manager) => {
    17. const expectedSalary = manager.calculateExpectedSalary();
    18. const experience = manager.getExperience();
    19. const portfolio = manager.getMBAProjects(); // 此处存在不同的地方,其余逻辑一样
    20. const data = {
    21. expectedSalary,
    22. experience,
    23. portfolio
    24. };
    25. render(data);
    26. });
    27. }
    28. //good
    29. class Developer {
    30. // ...
    31. getExtraDetails() {
    32. return {
    33. githubLink: this.githubLink,
    34. }
    35. }
    36. }
    37. class Manager {
    38. // ...
    39. getExtraDetails() {
    40. return {
    41. portfolio: this.portfolio,
    42. }
    43. }
    44. }
    45. private showEmployeeList(employee: Developer | Manager) {
    46. employee.forEach((employee) => {
    47. const expectedSalary = developer.calculateExpectedSalary();
    48. const experience = developer.getExperience();
    49. const extra = employee.getExtraDetails(); // 把不同的地方抽象出来,交给不同的实现处理
    50. const data = {
    51. expectedSalary,
    52. experience,
    53. extra,
    54. };
    55. render(data);
    56. });
    57. }

    避免副作用:

    函数完成本省功能外,还修还或者访问外部数据而造成一定程度改变系统环境。

    TypeScript 中,原类型是值传递,对象、数组是引用传递。如果给函数传入的是对象,那么这个对象可能在其他地方被修改,从而产生副作用。

    1. //bad
    2. / 全局变量 name
    3. let name = 'Robert C. Martin';
    4. function toBase64() {
    5. name = btoa(name);
    6. }
    7. toBase64(); // 产生了副作用
    8. console.log(name); // 实际上要打印的值已经不是 'Robert C. Martin'
    9. //good
    10. const name = 'Robert C. Martin';
    11. function toBase64(text:string):string {
    12. return btoa(text);
    13. }
    14. const encodedName = toBase64(name);
    15. console.log(name);

    用 Object.assign 或解构来设置默认

    Object.assign 方法用于将源对象的所有可枚举属性,复制到目标对象。可用此方法设置默认值,需要注意:

    • Object.assign 方法浅拷贝,意味着属性值是对象,那么目标对象拷贝的是这个对象的引用。

    • 同名属性替换,而非添加。

    • 数组当对象处理。

    1. //bad
    2. type MenuConfig = {title?: string, body?: string, buttonText?: string, cancellable?: boolean};
    3. function createMenu(config: MenuConfig) {
    4. config.title = config.title || 'Foo';
    5. config.body = config.body || 'Bar';
    6. config.buttonText = config.buttonText || 'Baz';
    7. config.cancellable = config.cancellable !== undefined ? config.cancellable : true;
    8. }
    9. const menuConfig = {
    10. title: null,
    11. body: 'Bar',
    12. buttonText: null,
    13. cancellable: true
    14. };
    15. createMenu(menuConfig)
    16. //good
    17. type MenuConfig = {title?: string, body?: string, buttonText?: string, cancellable?: boolean};
    18. function createMenu(config: MenuConfig) {
    19. const menuConfig = Object.assign({
    20. title: 'Foo',
    21. body: 'Bar',
    22. buttonText: 'Baz',
    23. cancellable: true
    24. }, config);
    25. }
    26. createMenu({ body: 'Bar' });
    27. //或者,也可以使用默认值的解构:
    28. type MenuConfig = {title?: string, body?: string, buttonText?: string, cancellable?: boolean};
    29. function createMenu({title = 'Foo', body = 'Bar', buttonText = 'Baz', cancellable = true}: MenuConfig) {
    30. // ...
    31. }
    32. createMenu({ body: 'Bar' });

    为了避免副作用,不允许显式传递 undefined 或 null 值。参见 TypeScript 编译器的 --strictnullcheck 选项。

    避免全局函数

    在 JavaScript 中污染全局非常不可取,一旦和其他库冲突,使用者在运行产生异常之前对此一无所知。

    例如:想要扩展 JavaScript 的 Array,增加一个 diff 方法,用于显示两个数组之间差异。通常会将 diff 写入 Array.prototype。如果另一个库也增加了 diff 方法,却用于查找数组的第一个元素和最后一个元素之间的区别?

    此时就发生冲突了,更好的办法是继承 Array,在子类中实现diff。

    1. //bad
    2. declare global {
    3. interface Array<T> {
    4. diff(other: T[]): Array<T>;
    5. }
    6. }
    7. if (!Array.prototype.diff){
    8. Array.prototype.diff = function <T>(other: T[]): T[] {
    9. const hash = new Set(other);
    10. return this.filter(elem => !hash.has(elem));
    11. };
    12. }
    13. //good
    14. class MyArray<T> extends Array<T> {
    15. diff(other: T[]): T[] {
    16. const hash = new Set(other);
    17. return this.filter(elem => !hash.has(elem));
    18. };
    19. }

    函数式编程

    尽量使用函数式编程,让数据转换过程管道化。

    1. //bad
    2. const contributions = [
    3. {
    4. name: 'Uncle Bobby',
    5. linesOfCode: 500
    6. }, {
    7. name: 'Suzie Q',
    8. linesOfCode: 1500
    9. }, {
    10. name: 'Jimmy Gosling',
    11. linesOfCode: 150
    12. }, {
    13. name: 'Gracie Hopper',
    14. linesOfCode: 1000
    15. }
    16. ];
    17. let totalOutput = 0;
    18. for (let i = 0; i < contributions.length; i++) {
    19. totalOutput += contributions[i].linesOfCode;
    20. }
    21. //good
    22. // 使用函数式编程,如下:
    23. const totalOutput = contributions.reduce((totalLines, output) => totalLines + output.linesOfCode, 0)

    封装判断条件

    对于复杂点的判断条件,封装成函数,提升可读性

    1. //bad
    2. if (subscription.isTrial || account.balance > 0) {
    3. // ...
    4. }
    5. //good
    6. function canActivateService(subscription: Subscription, account: Account) {
    7. return subscription.isTrial || account.balance > 0
    8. }
    9. if (canActivateService(subscription, account)) {
    10. // ...
    11. }

    避免否定判断

    1. //bad
    2. function isNotStudent(user: User) {
    3. // ...
    4. }
    5. if (isNotStudent(user)) {
    6. // ...
    7. }
    8. //good
    9. function isStudent(user: User) {
    10. // ...
    11. }
    12. if (!isStudent(user)) {
    13. // ...
    14. }

    避免类型检查

    TypeScript 是 JavaScript 的一个严格的语法超集,具有静态类型检查的特性。所以一定要指定变量、参数和返回值的类型,以充分利用此特性,能让重构、理解代码更容易。

    1. //bad
    2. function travelToTexas(vehicle: Bicycle | Car) {
    3. if (vehicle instanceof Bicycle) {
    4. vehicle.pedal(this.currentLocation, new Location('texas'));
    5. } else if (vehicle instanceof Car) {
    6. vehicle.drive(this.currentLocation, new Location('texas'));
    7. }
    8. }
    9. //good
    10. type Vehicle = Bicycle | Car;
    11. function travelToTexas(vehicle: Vehicle) {
    12. vehicle.move(this.currentLocation, new Location('texas'));
    13. }

    使用迭代器与生成器

    像使用流一样处理数据集合时,请使用生成器和迭代器。理由如下:

    • 将调用者与生成器实现解耦,在某种意义上说,由调用者决定要访问多少。

    • 延迟执行,按需使用。

    • 内置支持使用 for-of 语法进行迭代。

      1. //bad
      2. function fibonacci(n: number): number[] {
      3. if (n === 1) return [0];
      4. if (n === 2) return [0, 1];
      5. const items: number[] = [0, 1];
      6. while (items.length < n) {
      7. items.push(items[items.length - 2] + items[items.length - 1]);
      8. }
      9. return items;
      10. }
      11. function print(n: number) {
      12. fibonacci(n).forEach(fib => console.log(fib));
      13. }
      14. print(10);
      15. //good
      16. // 使用 Generator,yield 关键字用来暂停和继续执行一个生成器函数。
      17. function* fibonacci(): IterableIterator<number> {
      18. let [a, b] = [0, 1];
      19. while (true) {
      20. yield a;
      21. [a, b] = [b, a + b];
      22. }
      23. }
      24. function print(n: number) {
      25. let i = 0;
      26. for (const fib in fibonacci()) {
      27. if (i++ === n) break;
      28. console.log(fib);
      29. }
      30. }
      31. print(10);

    有些库通过链接 map、slice、forEach 等方法,达到与原生数组类似的方式处理迭代。参见 itiriri 里面有一些使用迭代器的高级操作示例(或异步迭代的操作 itiriri-async)。

    1. import itiriri from 'itiriri';
    2. function* fibonacci(): IterableIterator<number> {
    3. let [a, b] = [0, 1];
    4. while (true) {
    5. yield a;
    6. [a, b] = [b, a + b];
    7. }
    8. }
    9. itiriri(fibonacci())
    10. .take(10)
    11. .forEach(fib => console.log(fib));
  • 相关阅读:
    java毕业设计白天鹅造型网mybatis+源码+调试部署+系统+数据库+lw
    特征工程中的缩放和编码的方法总结
    Baumer工业相机堡盟工业相机如何通过NEOAPISDK使用PnPEventHandler实现相机掉线自动重连 (C#)
    第五十三周总结——云文档开发一周总结
    七牛云配置自定义域名
    视频流远程控制启动教程
    WatchDog:一款.NET开源的实时应用监控系统
    Performance火焰图
    Origin 导入数据画图使用经验总结
    智慧园区的核心本质是什么?
  • 原文地址:https://blog.csdn.net/weixin_44828588/article/details/127558969