美文网首页
TypeScript 代码整洁之道 - 变量

TypeScript 代码整洁之道 - 变量

作者: 小校有来有去 | 来源:发表于2019-02-18 19:00 被阅读3次

将 Clean Code 的概念适用到 TypeScript,灵感来自 clean-code-javascript
原文地址: clean-code-typescript
中文地址: clean-code-typescript

简介

这不是一份 TypeScript 设计规范,而是将 Robert C. Martin 的软件工程著作 《Clean Code》 适用到 TypeScript,指导读者使用 TypeScript 编写易读、可复用和易重构的软件。

变量

变量名要有意义

做有意义的区分,让读者更容易理解变量的含义。

反例:


function between<T>(a1: T, a2: T, a3: T) {

  return a2 <= a1 && a1 <= a3;

}

正例:


function between<T>(value: T, left: T, right: T) {

  return left <= value && value <= right;

}

变量名可拼读出来

如果你不能读出它,你在讨论它时听起来就会像个白痴。

反例:


class DtaRcrd102 {

  private genymdhms: Date;

  private modymdhms: Date;

  private pszqint = '102';

}

正例:


class Customer {

  private generationTimestamp: Date;

  private modificationTimestamp: Date;

  private recordId = '102';

}

对功能一致的变量采用统一命名

这个不难理解,看例子。

反例:


function getUserInfo(): User;

function getUserDetails(): User;

function getUserData(): User;

正例:


function getUser(): User;

变量名可检索

我们读代码要比写的多,所以易读性和可检索非常重要。如果不抽取变量并取有意义的名字,那就坑了读代码的人。使用 TSLint,它可以帮助识别未命名的常量。

反例:


// What the heck is 86400000 for?

setTimeout(restart, 86400000);

正例:


// Declare them as capitalized named constants.

const MILLISECONDS_IN_A_DAY = 24 * 60 * 60 * 1000;

setTimeout(restart, MILLISECONDS_IN_A_DAY);

使用自解释的变量名

变量名本身就能说明变量的含义。

反例:


declare const users:Map<string, User>;

for (const keyValue of users) {

  // iterate through users map

}

正例:


declare const users:Map<string, User>;

for (const [id, user] of users) {

  // iterate through users map

}

避免思维映射

不要让读者去猜测或想象变量的含义,明确是王道

反例:


const u = getUser();

const s = getSubscription();

const t = charge(u, s);

正例:


const user = getUser();

const subscription = getSubscription();

const transaction = charge(user, subscription);

不添加无用的上下文

如果类名或对象名已经表达了某些信息,在内部变量名中不要再重复表达。

反例:


type Car = {

  carMake: string;

  carModel: string;

  carColor: string;

}

function print(car: Car): void {

  console.log(`${this.carMake} ${this.carModel} (${this.carColor})`);

}

正例:


type Car = {

  make: string;

  model: string;

  color: string;

}

function print(car: Car): void {

  console.log(`${this.make} ${this.model} (${this.color})`);

}

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

通常,默认参数比短路更整洁。

反例:


function loadPages(count: number) {

  const loadCount = count !== undefined ? count : 10;

  // ...

}

正例:


function loadPages(count: number = 10) {

  // ...

}

相关文章

网友评论

      本文标题:TypeScript 代码整洁之道 - 变量

      本文链接:https://www.haomeiwen.com/subject/xwlzeqtx.html