diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..79fa890 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +# macOS +.DS_Store + +# IDE +.idea/ +.vscode/ diff --git a/README.md b/README.md index aacaf81..aff297b 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,31 @@ # Coding-Style-Guide +统一的代码规范仓库,旨在保障各语言项目代码的可读性、易维护性和编码安全性。 + +## 规范目录 + +| 语言 | 文档 | 参考基础 | +| --- | --- | --- | +| Golang | [go/hello_go.md](./go/hello_go.md) | [Google Golang 代码规范](https://github.com/golang/go/wiki/CodeReviewComments) | +| JavaScript | [javascript/hello_javascript.md](./javascript/hello_javascript.md) | [Airbnb JavaScript Style Guide](https://github.com/airbnb/javascript) | +| Python | [python/hello_python.md](./python/hello_python.md) | [PEP 8](https://www.python.org/dev/peps/pep-0008/) | + +## 规范等级 + +各语言规范中的每一条规则均标注了要求等级,含义一致: + +- **必须(Mandatory)**:必须采用,代码扫描工具将其视为错误; +- **推荐(Preferable)**:理应采用,特殊情况可以不采用,不计为错误; +- **可选(Optional)**:仅供参考,自行决定是否采用。 + +## 配套工具 + +- **Go**:`gofmt` / `goimports` / `go vet` / `golint` +- **JavaScript**:ESLint(规则包 + CI 增量/全量检查),可与 Prettier 配合 +- **Python**:`flake8` / `pylint` / `black` / EditorConfig + +## 使用建议 + +1. 新项目启动时,按所用语言选取对应规范作为团队约定基线; +2. 将规范接入代码扫描 / CI 流程,`必须` 级别规则以工具强制落地; +3. 未尽事宜以文件内已有风格、项目风格为准,保持一致性优先。 diff --git a/go/hello_go.md b/go/hello_go.md new file mode 100644 index 0000000..7b7ea49 --- /dev/null +++ b/go/hello_go.md @@ -0,0 +1,862 @@ +# Golang 代码规范 + +[TOC] + +## 1. 前言 + +为形成公司统一的 Go 编码风格,以保障公司项目代码的易维护性和编码安全性,特制定本规范。 + +本规范在 [Google Golang 代码规范](https://github.com/golang/go/wiki/CodeReviewComments) 的基础上,根据实际情况进行了调整和补充。 + +每项规范内容,给出了要求等级,其定义为: +- **必须(Mandatory)**:用户必须采用,代码扫描工具应将其视为错误; +- **推荐(Preferable)**:用户理应采用,但如有特殊情况,可以不采用,代码扫描工具不应将其视为错误; +- **可选(Optional)**:用户可参考,自行决定是否采用; + +目前本规范以 Gometalinter 工具落地,点击查看[工具源码](https://git.code.oa.com/codecheck-tools/goml_scan/tree/test)。 + + +License + +查看 [LICENSE](./LICENSE) 文件了解注明和鸣谢信息。 + + +## 2. 代码风格 + +### 2.1 【必须】格式化 + +- 代码都必须用 `gofmt` 格式化。 + +### 2.2 【推荐】换行 + +- 建议一行代码不要超过`120列`,超过的情况,使用合理的换行方法换行。 +- 例外场景: + - 函数签名(当然,这可能意味着你需要重新考虑是否传递了过多参数) + + ```go + // 长的函数签名可以超过列数限制 + func (i *webImpl) GenerateAgentInstallLink(ctx context.Context, req *pb.GenerateAgentInstallLinkRequest) (*pb.GenerateAgentInstallLinkResponse, error) { + ... + } + + // 不要在函数签名中为了满足推荐列数换行! + func (i *webImpl) GenerateAgentInstallLink(ctx context.Context, + req *pb.GenerateAgentInstallLinkRequest) (*pb.GenerateAgentInstallLinkResponse, error) { + ... // gofmt 会使签名与函数内语句对齐,导致代码可读性降低 + } + ``` + + - 长字符串文字(如果存在换行符 `\n`,应考虑使用原始字符串字面量 `` `raw string literal` ``) + + ```go + // 长的字符串可以超过列数限制 + pubkey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDPqE4yo8w7lezTpCkTt40whHoubL+0Qhsq1L3hF/lDW8zx1NpFTR9fC1HOqmUXj7tqPVg2xOAH+..." + + // 不要为了满足推荐列数换行并拼接字符串! + pubkey := "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQDPqE4yo8w7lezTpCkTt40whHoubL+0Qhsq1L3hF/lDW8zx1NpFTR9fC1HOqmUXj7tqPVg2xOAH+"+ + "zi2SqaZVeeXmsF5GAGFJcUylujr78Wf6od8//SApYx8RCSkRhGo8cTsxADlBCoTttJvk6Ocmy+uqEFXulsI0j+nh2x352eCExlDSqr0Me0J0LIGq/u9eqwhNN5k"+ + ... // 按列换行不会使代码更加可读,但会使字符串的搜索和修改更加困难! + + // 长的多行文本可以考虑使用原始字符串字面量 + tmpl := `some + long + tedious + template` + + // 注释中使用文档链接作为补充说明时,为了可读性和直接跳转可以超过列数限制 + // https://developer.hihonor.com/cn/kitdoc?category=%E5%9F%BA%E7%A1%80%E6%9C%8D%E5%8A%A1&kitId=11002&navigation=guides&docId=c+... + ``` + + - import 模块语句 + - 工具生成代码 + - struct tag + +### 2.3 【必须】括号和空格 + +- 遵循 `gofmt` 的逻辑。 + +- 运算符和操作数之间要留空格。 + +- 作为输入参数或者数组下标时,运算符和运算数之间不需要空格,紧凑展示。 + +### 2.4 【必须】import 规范 + +- 使用 `goimports` 自动格式化引入的包名,import 规范原则上以 `goimports` 规则为准。 + +- `goimports` 会自动把依赖包按首字母排序,并对包进行分组管理,通过空行隔开,默认分为本地包(标准库、内部包)、第三方包。 + +- 标准包永远位于最上面的第一组。 + +- 内部包是指不能被外部 import 的包,如 GoPath 模式下的包名或者非域名开头的当前项目的 GoModules 包名。 + +- 带域名的包名都属于第三方包,如 git.code.oa.com/xxx/xxx,github.com/xxx/xxx,不用区分是否是当前项目内部的包。 + +- `goimports` 默认最少分成本地包和第三方包两大类,这两类包必须分开不能放在一起。本地包或者第三方包内部可以继续按实际情况细分不同子类。 + +- 不要使用相对路径引入包: +```go +// 不要采用这种方式 +import ( + "../net" +) +``` + +- 应该使用完整的路径引入包: +```go +import ( + "xxxx.com/proj/net" +) +``` + +- 包名和 git 路径名不一致时,或者多个相同包名冲突时,使用别名代替,别名命名规范和包命名规范保持一致: +```go +// 合理用法:包名和 git 路径名不一致,使用别名 +import ( + opentracing "github.com/opentracing/opentracing-go" +) + +// 合理用法:多个相同包名冲突,使用别名 +import ( + "fmt" + "os" + "runtime/trace" + + nettrace "golang.net/x/trace" +) + + +// 不合理用法:包名和路径名一致,也不存在多包名冲突,并且原包名符合规范,则不应该使用别名 +import ( + "fmt" + "os" + + nettrace "golang.net/x/trace" +) + +``` + +- 【可选】第三方包的包名不符合规范可使用别名修正: +```go +import ( + qzone "git.code.oa.com/trpcprotocol/qqconnect/share_to_qzone" +) +``` + +- 【可选】匿名包的引用建议使用一个新的分组引入,并在匿名包上写上注释说明。 + +完整示例如下: +```go +import ( + // standard package & inner package + "encoding/json" + "myproject/models" + "myproject/controller" + "strings" + + // third-party package + "git.obc.im/obc/utils" + "git.obc.im/dep/beego" + "git.obc.im/dep/mysql" + opentracing "github.com/opentracing/opentracing-go" + + // anonymous import package + // import filesystem storage driver + _ "git.code.oa.com/org/repo/pkg/storage/filesystem +) +``` + +- 例外包 + - embed 当使用embed内嵌外部数据时不需要注释 + +### 2.5 【必须】错误处理 + +阅读 https://go.dev/doc/effective_go#errors 学习 go 错误处理机制的设计。 + +#### 2.5.1 【必须】error 处理 +- `error` 作为函数的值返回,必须对 `error` 进行处理, 或将返回值赋值给明确忽略。对于 `defer xx.Close()`可以不用显式处理。 + +- `error` 作为函数的值返回且有多个返回值的时候,`error` 必须是最后一个参数。 +```go +// 不要采用这种方式 +func do() (error, int) { + +} + +// 要采用下面的方式 +func do() (int, error) { + +} +``` + +- 错误描述不需要标点结尾。 + +- 采用独立的错误流进行处理。 +```go +// 不要采用这种方式 +if err != nil { + // error handling +} else { + // normal code +} + +// 而要采用下面的方式 +if err != nil { + // error handling + return // or continue, etc. +} +// normal code +``` + +- 如果返回值需要初始化,则采用下面的方式: +```go +x, err := f() +if err != nil { + // error handling + return // or continue, etc. +} +// use x +``` + +- 错误返回的判断独立处理,不与其他变量组合逻辑判断。 +```go +// 不要采用这种方式: +x, y, err := f() +if err != nil || y == nil { + return err // 当y与err都为空时,函数的调用者会出现错误的调用逻辑 +} + +// 应当使用如下方式: +x, y, err := f() +if err != nil { + return err +} +if y == nil { + return errors.New("some error") +} +``` + + +- 【推荐】对于不需要格式化的错误,生成方式为:`errors.New("xxxx")`。 +- 【推荐】建议go1.13 以上,error 生成方式为:`fmt.Errorf("module xxx: %w", err)`。 + +#### 2.5.2 【必须】panic 处理 +- 不要使用 `panic` 进行一般的错误处理,使用 `error` 和多返回值。 +- 可使用 panic 对不变量([invariant](https://en.wikipedia.org/wiki/Invariant_(mathematics)#Invariants_in_computer_science))进行断言。 + +```go +// 不要对用户输入进行断言,使用错误返回! +v, err := strconv.Atoi(userInputFromKeyboard) +if err != nil { + panic(fmt.Errorf("invalid user input: %v", err)) +} + +// 可以对不变量进行断言 +// readText 读取 n 中的文本内容。Node 必须为 TextNode 或 CommentNode。 +func readText(n Node) string { + switch n := n.(type) { + case *TextNode: + return n.Text + case *CommentNode: + return n.Comment + default: + panic(fmt.Errorf("unexpected node type: %T", n)) + } +} +``` + +- 在 `func init()` 及其调用的函数中,当初始化失败影响程序运行时,可以 `panic`,例如:读取本地文件系统中的配置文件。 + +- 在全局变量初始时调用的函数中,当初始化失败影响程序运行时,可以 `panic`,例如:`regexp.MustCompile`,`template.Must`。 + +- 导出的方法一般不允许 `panic`。因特殊情况必须 `panic` 的方法应使用 `MustXXX` 的方式进行命名,并在文档中加以说明。 + +- 不建议使用 `log.Fatal` 进行断言:log 库必须初始化才可以使用;log 库可能无法正确显示堆栈信息;log 库在 `panic` 时可能无法有效的保留错误信息。 + +#### 2.5.3 【必须】recover 处理 +- 必须在 `defer` 中使用。 + +- 在业务逻辑中一般不需要使用 `recover`。 + +- `recover` 用于捕获具有明确类型的 `panic`,禁止滥用 `recover` 捕获全部类型的异常。 + +```go +// FatalError 为包内定义的错误类型 +type FatalError string + +func (e FatalError) Error() string { return string(e) } + +func main() { + defer func() { + e := recover() // 注意,recover 返回的是 interface{},不要假设其是 error,因此不要将返回值命名为 err。 + if e != nil { + err, ok := e.(FatalError) + if !ok { + // 继续抛出不认识的异常 + panic(e) + } + // 响应抛出的错误 + } + }() + panic(FatalError("错误信息")) +} +``` + +### 2.6 【必须】单元测试 +- 单元测试文件名命名规范为 `example_test.go`。 + +- 测试用例的函数名称必须以 `Test` 开头,例如 `TestExample`。 + +- 如果存在 `func Foo`,单测函数可以带下划线,为 `func Test_Foo`。如果存在 `func (b *Bar) Foo`,单测函数可以为 `func TestBar_Foo`。下划线不能出现在前面描述情况以外的位置。 + +- 单测文件行数限制是普通文件的2倍,即`1600行`。单测函数行数限制也是普通函数的2倍,即为`160行`。圈复杂度、列数限制、 import 分组等其他规范细节和普通文件保持一致。 + +- 由于单测文件内的函数都是不对外的,所有可导出函数可以没有注释,但是结构体定义时尽量不要导出。 + +- 每个重要的可导出函数都要首先编写测试用例,测试用例和正规代码一起提交方便进行回归测试。 + +## 3. 注释 +- 在编码阶段同步写好变量、函数、包注释,注释可以通过 `godoc` 导出生成文档。 +- 程序中每一个被导出的(大写的)名字,都应该有一个文档注释。注意,非导出类型的方法(`func (*privateType) Method()`)可以没有文档注释。 +- 所有注释掉的代码在提交 code review 前都应该被删除,除非添加注释讲解为什么不删除, 并且标明后续处理建议(比如删除计划)。 + +### 3.1 【必须】包注释 +- 每个包都应该有一个包注释(main包除外)。 + +- 包如果有多个 go 文件,只需要出现在一个 go 文件中(一般是和包同名的文件)即可,格式为:“// Package 包名 包信息描述”。 + +```go +// Package math provides basic constants and mathematical functions. +package math + +// 或者 + +/* +Package template implements data-driven templates for generating textual +output such as HTML. +.... +*/ +package template +``` + +### 3.2 【必须】结构体注释 +- 每个需要导出的自定义结构体或者接口都必须有注释说明。 + +- 注释对结构进行简要介绍,放在结构体定义的前一行。 + +- 格式为:"// 结构体名 结构体信息描述"。 + +- 结构体内的可导出成员变量名,如果是个生僻词,或者意义不明确的词,就必须要给出注释,放在成员变量的前一行或同一行的末尾。 +```go +// User 用户结构定义了用户基础信息 +type User struct { + Name string + Email string + // Demographic 族群 + Demographic string +} +``` + +### 3.3 【必须】方法注释 +- 每个需要导出的函数或者方法(结构体或者接口下的函数称为方法)都必须有注释。注意,如果方法的接收器为不可导出类型,可以不注释,但需要质疑该方法可导出的必要性。 + +- 注释描述函数或方法功能、调用方等信息。 + +- 格式为:"// 函数名 函数信息描述"。 +```go +// NewtAttrModel 是属性数据层操作类的工厂方法 +func NewAttrModel(ctx *common.Context) *AttrModel { + // TODO +} +``` + +- 例外方法: + - Write Read 用于常见IO + - ServeHTTP 用于HTTP服务 + - String 用于打印 + - Unwrap Error 用于错误处理 + - Len Less Swap 用于排序 + +### 3.4 【必须】变量和常量注释 +- 每个需要导出的常量和变量都必须有注释说明。 + +- 该注释对常量或变量进行简要介绍,放在常量或者变量定义的前一行。 + +- 大块常量或变量定义时,可在前面注释一个总的说明,然后每一行常量的末尾详细注释该常量的定义。 + +- 格式为:"// 变量名 变量信息描述",斜线后面紧跟一个空格。 +```go +// FlagConfigFile 配置文件的命令行参数名 +const FlagConfigFile = "--config" + +// 命令行参数 +const ( + FlagConfigFile1 = "--config" // 配置文件的命令行参数名1 + FlagConfigFile2 = "--config" // 配置文件的命令行参数名2 + FlagConfigFile3 = "--config" // 配置文件的命令行参数名3 + FlagConfigFile4 = "--config" // 配置文件的命令行参数名4 +) + +// FullName 返回指定用户名的完整名称 +var FullName = func(username string) string { + return fmt.Sprintf("fake-%s", username) +} +``` + +### 3.5 【必须】类型注释 +- 每个需要导出的类型定义(type definition)和类型别名(type aliases)都必须有注释说明。 + +- 该注释对类型进行简要介绍,放在定义的前一行。 + +- 格式为:"// 类型名 类型信息描述"。 +```go +// StorageClass 存储类型 +type StorageClass string + +// FakeTime 标准库时间的类型别名 +type FakeTime = time.Time +``` + +## 4. 命名规范 +命名是代码规范中很重要的一部分,统一的命名规范有利于提高代码的可读性,好的命名仅仅通过命名就可以获取到足够多的信息。 + +### 4.1 【推荐】包命名 +- 保持 `package` 的名字和目录一致。 + +- 尽量采取有意义、简短的包名,尽量不要和标准库冲突。 + +- 包名应该为小写单词,不要使用下划线或者混合大小写,使用多级目录来划分层级。 + +- 包名可谨慎地使用缩写。当缩写是程序员广泛熟知的词时,可以使用缩写。例如: + + strconv (string conversion) + + syscall (system call) + + fmt (formatted I/O) + + 如果缩写有歧义或不清晰,不用缩写。 + +- 项目名可以通过中划线来连接多个单词。 + +- 简单明了的包命名,如:`time`、`list`、`http`。 + +- 不要使用无意义的包名,如:`util`、`common`、`misc`、`global`。`package`名字应该追求清晰且越来越收敛,符合‘单一职责’原则。而不是像`common`一样,什么都能往里面放,越来越膨胀,让依赖关系变得复杂,不利于阅读、复用、重构。注意,`xx/util/encryption`这样的包名是允许的。 + +### 4.2 【必须】文件命名 +- 采用有意义,简短的文件名。 + +- 文件名应该采用小写,并且使用下划线分割各个单词。 + +### 4.3 【必须】结构体命名 +- 采用驼峰命名方式,首字母根据访问控制采用大写或者小写。 + +- 结构体名应该是名词或名词短语,如 `Customer`、`WikiPage`、`Account`、`AddressParser`,它不应是动词。 + +- 避免使用 `Data`、`Info` 这类意义太宽泛的结构体名。 + +- 结构体的声明和初始化格式采用多行,例如: +```go +// User 多行声明 +type User struct { + Name string + Email string +} + +// 多行初始化 +u := User{ + Name: "john", + Email: "john@example.com", +} +``` + +### 4.4 【推荐】接口命名 +- 命名规则基本保持和结构体命名规则一致。 + +- 单个函数的接口名以 `er` 作为后缀,例如 `Reader`,`Writer`。 +```go +// Reader 字节数组读取接口 +type Reader interface { + // Read 读取整个给定的字节数据并返回读取的长度 + Read(p []byte) (n int, err error) +} +``` + +- 两个函数的接口名综合两个函数名。 + +- 三个以上函数的接口名,类似于结构体名。 +```go +// Car 小汽车结构申明 +type Car interface { + // Start ... + Start([]byte) + // Stop ... + Stop() error + // Recover ... + Recover() +} +``` + +### 4.5 【必须】变量命名 +- 变量名必须遵循驼峰式,首字母根据访问控制决定使用大写或小写。 + +- 特有名词时,需要遵循以下规则: + - 如果变量为私有,且特有名词为首个单词,则使用小写,如 `apiClient`; + - 其他情况都应该使用该名词原有的写法,如 `APIClient`、`repoID`、`UserID`; + - 错误示例:`UrlArray`,应该写成 `urlArray` 或者 `URLArray`; + - 详细的专有名词列表可参考[这里](https://github.com/golang/lint/blob/738671d3881b9731cc63024d5d88cf28db875626/lint.go#L770)。 + +- 私有全局变量和局部变量规范一致,均以小写字母开头。 + +- 代码生成工具自动生成的代码可排除此规则(如 xxx.pb.go 里面的 Id)。 + +- 变量名更倾向于选择短命名。特别是对于局部变量。 `c`比`lineCount`要好,`i`比`sliceIndex`要好。基本原则是:变量的使用和声明的位置越远,变量名就需要具备越强的描述性。 + +### 4.6 【必须】常量命名 +- 常量均需遵循驼峰式。 +```go +// AppVersion 应用程序版本号定义 +const AppVersion = "1.0.0" +``` + +- 如果是枚举类型的常量,需要先创建相应类型: +```go +// Scheme 传输协议 +type Scheme string + +const ( + // HTTP 表示HTTP明文传输协议 + HTTP Scheme = "http" + // HTTPS 表示HTTPS加密传输协议 + HTTPS Scheme = "https" +) +``` + +- 私有全局常量和局部变量规范一致,均以小写字母开头。 +```go +const appVersion = "1.0.0" +``` + +### 4.7 【必须】函数命名 +- 函数名必须遵循驼峰式,首字母根据访问控制决定使用大写或小写。 +- 代码生成工具自动生成的代码可排除此规则(如协议生成文件 xxx.pb.go , gotests 自动生成文件 xxx_test.go 里面的下划线)。 + +## 5. 控制结构 + +### 5.1 【推荐】if +- `if` 接受初始化语句,约定如下方式建立局部变量: +```go +if err := file.Chmod(0664); err != nil { + return err +} +``` + +- `if` 对两个值进行判断时,约定如下顺序:变量在左,常量在右: +```go +// 不要采用这种方式 +if nil != err { + // error handling +} + +// 不要采用这种方式 +if 0 == errorCode { + // do something +} + +// 而要采用下面的方式 +if err != nil { + // error handling +} + +// 而要采用下面的方式 +if errorCode == 0 { + // do something +} +``` + +- `if` 对于bool类型的变量,应直接进行真假判断: +```go +var allowUserLogin bool +// 不要采用这种方式 +if allowUserLogin == true { + // do something +} + +// 不要采用这种方式 +if allowUserLogin == false { + // do something +} + +// 而要采用下面的方式 +if allowUserLogin { + // do something +} + +// 而要采用下面的方式 +if !allowUserLogin { + // do something +} +``` + +### 5.2 【推荐】for +- 采用短声明建立局部变量: +```go +sum := 0 +for i := 0; i < 10; i++ { + sum += 1 +} +``` + +### 5.3 【必须】range +- 如果只需要第一项(key),就丢弃第二个: +```go +for key := range m { + if key.expired() { + delete(m, key) + } +} +``` + +- 如果只需要第二项,则把第一项置为下划线: +```go +sum := 0 +for _, value := range array { + sum += value +} +``` + +### 5.4 【必须】switch +- 要求必须有 `default`: +```go +switch os := runtime.GOOS; os { + case "darwin": + fmt.Println("OS X.") + case "linux": + fmt.Println("Linux.") + default: + // freebsd, openbsd, + // plan9, windows... + fmt.Printf("%s.\n", os) +} +``` + +### 5.5 【推荐】return +- 尽早 `return`,一旦有错误发生,马上返回: +```go +f, err := os.Open(name) +if err != nil { + return err +} + +defer f.Close() + +d, err := f.Stat() +if err != nil { + return err +} + +codeUsing(f, d) +``` +### 5.6 【必须】goto +- 业务代码禁止使用 `goto`,其他框架或底层源码推荐尽量不用。 + +## 6. 函数 + +### 6.1 【推荐】函数参数 +- 函数返回相同类型的两个或三个参数,或者如果从上下文中不清楚结果的含义,使用命名返回,其它情况不建议使用命名返回。 +```go +// Parent1 ... +func (n *Node) Parent1() *Node + +// Parent2 ... +func (n *Node) Parent2() (*Node, error) + +// Location ... +func (f *Foo) Location() (lat, long float64, err error) +``` + +- 传入变量和返回变量以小写字母开头。 + +- 参数数量均不能超过`5个`。 + +- 尽量用值传递,非指针传递。 + +- 传入参数是 `map`,`slice`,`chan`,`interface` 不要传递指针。 + +### 6.2 【必须】defer +- 当存在资源管理时,应紧跟 `defer` 函数进行资源的释放。 + +- 判断是否有错误发生之后,再 `defer` 释放资源。 +```go +resp, err := http.Get(url) +if err != nil { + return err +} +// 如果操作成功,再defer Close() +defer resp.Body.Close() +``` + +- 禁止在循环中使用 `defer`,举例如下: +```go +// 不要这样使用 +func filterSomething(values []string) { + for _, v := range values { + fields, err := db.Query(v) // 示例,实际不要这么查询,防止sql注入 + if err != nil { + // xxx + } + defer fields.Close() + // 继续使用fields + } +} + +// 应当使用如下的方式: +func filterSomething(values []string) { + for _, v := range values { + func() { + fields, err := db.Query(v) // 示例,实际不要这么查询,防止sql注入 + if err != nil { + ... + } + defer fields.Close() + // 继续使用fields + }() + } +} +``` + +### 6.3 【推荐】方法的接收器 +- 【推荐】推荐以类名第一个英文首字母的小写作为接收器的命名。 + +- 【推荐】接收器的命名在函数超过`20行`的时候不要用单字符。 + +- 【必须】命名不能采用 `me`,`this`,`self` 这类易混淆名称。 + +### 6.4 【推荐】代码行数 +- 【必须】文件长度不能超过`800行`。 + +- 【推荐】函数长度不能超过`80行`(函数长度为函数签名左括号下一行开始到右括号上一行结束部分的行数,包括代码行,注释行,空行)。 + +### 6.5 【必须】嵌套 +- 嵌套深度不能超过`4层`: +```go +// AddArea 添加成功或出错 +func (s *BookingService) AddArea(areas ...string) error { + s.Lock() + defer s.Unlock() + + for _, area := range areas { + for _, has := range s.areas { + if area == has { + return srverr.ErrAreaConflict + } + } + s.areas = append(s.areas, area) + s.areaOrders[area] = new(order.AreaOrder) + } + return nil +} +``` + +```go +// 建议调整为这样: + +// AddArea 添加成功或出错 +func (s *BookingService) AddArea(areas ...string) error { + s.Lock() + defer s.Unlock() + + for _, area := range areas { + if s.HasArea(area) { + return srverr.ErrAreaConflict + } + s.areas = append(s.areas, area) + s.areaOrders[area] = new(order.AreaOrder) + } + return nil +} + +// HasArea ... +func (s *BookingService) HasArea(area string) bool { + for _, has := range s.areas { + if area == has { + return true + } + } + return false +} +``` + +### 6.6 【推荐】变量声明 +- 变量声明尽量放在变量第一次使用前面,就近原则。 + +### 6.7 【必须】魔法数字 +魔数应使用常量或变量做替代。 + +魔数常常具有以下特征: +- 缺乏解释或命名的表示相同含义的独特数值,对读者来说难以理解,影响可读性 +- 在程序中出现多次,当数值改变时,可能要改不只一个地方 + +例如: +```go +total := 1.05 * price +// 应改写为 +const TaxRate = 0.05 +total := (1.0 + TaxRate) * price +``` + +正确的使用命名量替代魔数可以改善可读性,但是也存在代价: + +- 如果命名量与使用处距离很远,则会破坏代码的局部性,使代码的理解更加困难 + +```go +// 不要这样做! +const ( + ... + appNameFormatErrorMsgFormat = "the app name is incorrect: %q" + userNameFormatErrorMsgFormat = "the user name is invalid: %q" + ... +) +... 省略 100 行 ... +func ParseAppName(v string) error { + ... + return fmt.Errorf(appNameFormatErrorMsgFormat, v) // 开发者无法直接知道需要传入几个参数,也无法通过错误信息直接找到产生错误的位置 +} +``` + +- 它可能使代码更加冗长 +- 它可能使代码运行更慢(从编译时计算变成运行时计算) + + +因此,正确识别魔数非常重要。一般而言,只要在上下文中能让人一眼明白其含义,并且基本没有需要改变的可能,就不会被认为是魔术数字。常见的例子包括: +```go +d = b*b - 4*a*c // 一元二次方程判别式公式中的 4 +if x%2 == 0 {} // 中的 2 +for i := 0; i < max; i += 1 {} // 中的 0 和 1 +os.Exit(1) // 表示程序错误的 1(当然,如果需要区分多种不同的错误,则应该为不同的退出值进行命名) +scn.Buffer(nil, 10<<20) // 中的 10<<20 +strings.IndexOf(s, ":") == -1 // 中的 ":" 和 -1 +``` + +## 7. 依赖管理 +### 7.1 【必须】go1.11 以上必须使用 `go modules` 模式: +```go +go mod init git.woa.com/group/myrepo +``` +### 7.2 【推荐】代码提交 +- 建议所有不对外开源的工程的 `module name` 使用 `git.woa.com/group/repo` ,方便他人直接引用。 + +- 建议使用 `go modules` 作为依赖管理的项目不提交 `vendor` 目录。 + +- 建议使用 `go modules` 管理依赖的项目, `go.sum` 文件必须提交,不要添加到 .gitignore 规则中。 + + +## 8. 应用服务 +### 8.1 【推荐】应用服务接口建议有 `README.md` +- 其中建议包括服务基本描述、使用方法、部署时的限制与要求、基础环境依赖(例如最低 go 版本、最低外部通用包版本)等。 + +### 8.2 【必须】应用服务必须要有接口测试。 + + +## 附:常用工具 +go 语言本身在代码规范性这方面也做了很多努力,很多限制都是强制语法要求,例如左大括号不换行,引用的包或者定义的变量不使用会报错,此外 go 还是提供了很多好用的工具帮助我们进行代码的规范。 +- `gofmt` ,大部分的格式问题可以通过 `gofmt` 解决, `gofmt` 自动格式化代码,保证所有的 go 代码与官方推荐的格式保持一致,于是所有格式有关问题,都以 `gofmt` 的结果为准。 +- `goimports` ,此工具在 `gofmt` 的基础上增加了自动删除和引入包。 +- `go vet` ,`vet` 工具可以帮我们静态分析我们的源码存在的各种问题,例如多余的代码,提前 `return` 的逻辑, `struct` 的 `tag` 是否符合标准等。编译前先执行代码静态分析。 +- `golint` ,类似 `javascript` 中的 `jslint` 的工具,主要功能就是检测代码中不规范的地方。 \ No newline at end of file diff --git a/javascript/hello_javascript.md b/javascript/hello_javascript.md new file mode 100644 index 0000000..07d930b --- /dev/null +++ b/javascript/hello_javascript.md @@ -0,0 +1,4232 @@ +# JavaScript 编码规范 + +[TOC] + +## 前言 + +为前端开发提供良好的基础编码风格修行指南。 + +基于 [Airbnb](https://github.com/airbnb/javascript#table-of-contents) 编码规范。所有规范分为三个等级:**必须**、**推荐**、**可选**。 + +**必须(Mandatory)** 级别要求员工必须严格按照规范的编码格式编写,否则会在代码扫描和自动化构建中报错。对应 [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt) 中的 `MUST`, `MUST NOT` 和 `REQUIRED` 级别。 + +**推荐(Preferable)** 级别希望员工尽量按照规范编写,但如有特殊情况,可以不采用。对应 [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt) 中的 `SHOULD`, `SHOULD NOT` 级别。 + +**可选(Optional)** 级别并不对员工编码提出要求,一般是JavaScript常识以及ES6、ES7的新语法,但仍希望员工按参考规范编写。委员会将定期review编码规范,不断提高规范等级要求。对应 [RFC 2119](https://www.ietf.org/rfc/rfc2119.txt) 中的 `MAY` 级别。 + +本文档中的代码为示例代码,出于演示目的,不一定完全符合本文档所规定的所有规则要求。 + +本文档中的示例代码中会有 Good 或 Best 的提示,表示这是遵守代码规范的一种写法。 +需要说明的是,虽然 Good 写法符合这条规范,但不代表这是满足规范的唯一方式。 + +未尽事宜,应当首先以同一文件中的其他类似风格为准,若该文件中没有类似结构,则以项目风格为准。一致性是最重要的。 + +### License + +基于 MIT 协议开源。 + +查看 [Notice](./NOTICE) 文件了解注明和鸣谢信息。 + +## 0. 相关工具 + +### eslint-config-xxxxxx 规则包 + +安装: + +javascript + +```shell +tnpm install eslint @xxxxxx/eslint-config-xxxxxx --save-dev +``` + +#### ESLint 传统配置 Legacy Config + +_.eslintrc.js:_ + +```javascript +module.exports = { + extends: ['@xxxxxx/eslint-config-xxxxxx'], +} +``` + +typescript 还需要安装依赖 + +```shell +tnpm install @typescript-eslint/eslint-plugin @typescript-eslint/parser --save-dev +``` + +_.eslintrc.js:_ + +```javascript +module.exports = { + extends: ['@xxxxxx/eslint-config-xxxxxx', '@xxxxxx/eslint-config-xxxxxx/ts'], +} +``` + +使用 prettier 的用户需要安装对应的依赖 + +```shell +tnpm install prettier eslint-plugin-prettier --save-dev +``` + +_.eslintrc.js:_ + +```javascript +module.exports = { + extends: ['@xxxxxx/eslint-config-xxxxxx', '@xxxxxx/eslint-config-xxxxxx/ts', '@xxxxxx/eslint-config-xxxxxx/prettier'], +} +``` + +**注意:使用 prettier 规则之后,会自动禁用掉与之相冲突的格式相关的规则。由于prettier与ESLint存在冲突,开源扫描仍以ESLint扫描结果为准。** + +#### ESLint 新版扁平配置 Flat Config + +推荐使用 cjs 作为配置文件后缀,可兼容 type: module 和 type: commonjs 的项目。 + +eslint.config.cjs: + +```js +const xxxxxxEslintConfig = require('@xxxxxx/eslint-config-xxxxxx/flat'); +module.exports = xxxxxxEslintConfig({}); +``` + +使用 TypeScript 的项目需要传入 `tsconfig.json` 所在的目录位置, + +eslint.config.cjs: + +```js +const xxxxxxEslintConfig = require('@xxxxxx/eslint-config-xxxxxx/flat'); +module.exports = xxxxxxEslintConfig({ + tsconfigRootDir: __dirname, +}); +``` + +### Orange-ci 插件 + +增量检查 + +```yaml +master: + merge_request: + - stages: + - name: make changelist + type: git:changeList + options: + changed: changed.txt + - name: git diff eslint-config-xxxxxx + image: csighub.xxxxxxyun.com/standards/eslint-config-xxxxxx:latest + settings: + change_file: changed.txt +``` + +全量检查 + +```yaml +master: + merge_request: + - stages: + - name: git eslint-config-xxxxxx + image: csighub.xxxxxxyun.com/standards/eslint-config-xxxxxx:latest +``` + +### 工蜂CI 插件 + +全量检查 + +```yaml +mr: + branches: + include: + - master +stages: + - stage: + - job: + name: eslint + steps: + - taskType: dockerRun@latest + displayName: dockerRun + inputs: + image: csighub.xxxxxxyun.com/standards/eslint-config-xxxxxx:latest + cmd: "" +``` + +## 1. 类型 + +- [1.1](#types--primitives) **【可选】 基本类型**: 当你访问一个基本类型时,直接操作它的值。 + + - `string` + - `number` + - `boolean` + - `null` + - `undefined` + - `symbol` + + ```javascript + const foo = 1; + let bar = foo; + + bar = 9; + + console.log(foo, bar); // => 1, 9 + ``` + + - 符号(Symbols)不能完全的被 [polyfill](https://en.wikipedia.org/wiki/Polyfill_(programming)),因此在不能原生支持symbol类型的浏览器或环境中,不应该使用symbol类型。 + +- [1.2](#types--complex) **【可选】 复杂类型**: 当你访问一个复杂类型时,直接操作其值的引用。 + + - `object` + - `array` + - `function` + + ```javascript + const foo = [1, 2]; + const bar = foo; + + bar[0] = 9; + + console.log(foo[0], bar[0]); // => 9, 9 + ``` + +## 2. 引用 + +- [2.1](#references--prefer-const) **【必须】** 使用 `const` 定义你的所有引用;避免使用 `var`。 eslint: [`prefer-const`](https://eslint.org/docs/rules/prefer-const.html), [`no-const-assign`](https://eslint.org/docs/rules/no-const-assign.html) + + > 原因? 这样能够确保你不能重新赋值你的引用,否则可能导致错误或者产生难以理解的代码。 + + ```javascript + // bad + var a = 1; + var b = 2; + + // good + const a = 1; + const b = 2; + ``` + +- [2.2](#references--disallow-var) **【必须】** 如果你必须重新赋值你的引用, 使用 `let` 代替 `var`。 eslint: [`no-var`](https://eslint.org/docs/rules/no-var.html) + + > 原因? `let` 是块级作用域,而不像 `var` 是函数作用域。 + + ```javascript + // bad + var count = 1; + if (true) { + count += 1; + } + + // good, use the let. + let count = 1; + if (true) { + count += 1; + } + ``` + +- [2.3](#references--block-scope) **【可选】** 注意,let 和 const 都是块级作用域。 + + ```javascript + // const 和 let 只存在于他们定义的块级作用域中。 + { + let a = 1; + const b = 1; + } + console.log(a); // ReferenceError + console.log(b); // ReferenceError + ``` + +## 3. 对象 + +- [3.1](#objects--no-new) **【必须】** 使用字面量语法创建对象。 eslint: [`no-new-object`](https://eslint.org/docs/rules/no-new-object.html) + + ```javascript + // bad + const item = new Object(); + + // good + const item = {}; + ``` + +- [3.2](#es6-computed-properties) **【推荐】** 在创建具有动态属性名称的对象时使用计算属性名。 + + > 原因? 它允许你在一个地方定义对象的所有属性。 + + ```javascript + function getKey(k) { + return `a key named ${k}`; + } + + // bad + const obj = { + id: 5, + name: 'San Francisco', + }; + obj[getKey('enabled')] = true; + + // good + const obj = { + id: 5, + name: 'San Francisco', + [getKey('enabled')]: true, + }; + ``` + +- [3.3](#es6-object-shorthand) **【推荐】** 用对象方法简写。 eslint: [`object-shorthand`](https://eslint.org/docs/rules/object-shorthand.html) + + ```javascript + // bad + const value = 1; + const atom = { + value: value, + addValue: function (newValue) { + return atom.value + newValue; + }, + }; + + // good + const value = 1; + const atom = { + value, + addValue(newValue) { + return atom.value + newValue; + }, + }; + ``` + +- [3.4](#es6-object-concise) **【推荐】** 用属性值简写。 eslint: [`object-shorthand`](https://eslint.org/docs/rules/object-shorthand.html) + + > 原因? 它更加简洁并更具描述性。 + + ```javascript + const lukeSkywalker = 'Luke Skywalker'; + + // bad + const obj = { + lukeSkywalker: lukeSkywalker, + }; + + // good + const obj = { + lukeSkywalker, + }; + ``` + +- [3.5](#objects--grouped-shorthand) **【推荐】** 声明对象时,将简写的属性放在前面。 + + > 原因? 这样更容易的判断哪些属性使用的简写。 + + ```javascript + const anakinSkywalker = 'Anakin Skywalker'; + const lukeSkywalker = 'Luke Skywalker'; + + // bad + const obj = { + episodeOne: 1, + twoJediWalkIntoACantina: 2, + lukeSkywalker, + episodeThree: 3, + mayTheFourth: 4, + anakinSkywalker, + }; + + // good + const obj = { + lukeSkywalker, + anakinSkywalker, + episodeOne: 1, + twoJediWalkIntoACantina: 2, + episodeThree: 3, + mayTheFourth: 4, + }; + ``` + +- [3.6](#objects--quoted-props) **【必须】** 只使用引号标注无效标识符的属性。 eslint: [`quote-props`](https://eslint.org/docs/rules/quote-props.html) + + > 原因? 一般来说,我们认为这样更容易阅读。 它能更好地适配语法高亮显示功能,并且更容易通过许多 JS 引擎进行优化。 + + ```javascript + // bad + const bad = { + 'foo': 3, + 'bar': 4, + 'data-blah': 5, + }; + + // good + const good = { + foo: 3, + bar: 4, + 'data-blah': 5, + }; + ``` + +- [3.7](#objects--prototype-builtins) **【推荐】** 不能直接调用 `Object.prototype` 的方法,如: `hasOwnProperty` 、 `propertyIsEnumerable` 和 `isPrototypeOf`。 eslint: [`no-prototype-builtins`](https://eslint.org/docs/rules/no-prototype-builtins.html) + + > 原因? 这些方法可能被有问题的对象上的属性覆盖 - 如 `{ hasOwnProperty: false }` - 或者,对象是一个空对象 (`Object.create(null)`)。 + + ```javascript + // bad + console.log(object.hasOwnProperty(key)); + + // good + console.log(Object.prototype.hasOwnProperty.call(object, key)); + + // best + const has = Object.prototype.hasOwnProperty; // 在模块范围内的缓存中查找一次 + console.log(has.call(object, key)); + + /* or */ + import has from 'has'; // https://www.npmjs.com/package/has + console.log(has(object, key)); + ``` + +- [3.8](#objects--rest-spread) **【推荐】** 使用对象扩展操作符(spread operator)浅拷贝对象,而不是用 [`Object.assign`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/assign) 方法。 使用对象的剩余操作符(rest operator)来获得一个新对象,该对象省略了某些属性。 eslint: [`prefer-object-spread`](https://eslint.org/docs/rules/prefer-object-spread) + + ```javascript + // very bad + const original = { a: 1, b: 2 }; + const copy = Object.assign(original, { c: 3 }); // 变异的 `original` ಠ_ಠ + delete copy.a; // 这.... + + // bad + const original = { a: 1, b: 2 }; + const copy = Object.assign({}, original, { c: 3 }); // copy => { a: 1, b: 2, c: 3 } + + // good + const original = { a: 1, b: 2 }; + const copy = { ...original, c: 3 }; // copy => { a: 1, b: 2, c: 3 } + + const { a, ...noA } = copy; // noA => { b: 2, c: 3 } + ``` + +## 4. 数组 + +- [4.1](#arrays--literals) **【必须】** 使用字面量语法创建数组。 eslint: [`no-array-constructor`](https://eslint.org/docs/rules/no-array-constructor.html) + + ```javascript + // bad + const items = new Array(); + + // good + const items = []; + ``` + +- [4.2](#arrays--push) **【必须】** 使用 [Array#push](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push) 代替直接赋值来给数组添加项。 + + ```javascript + const someStack = []; + + // bad + someStack[someStack.length] = 'abracadabra'; + + // good + someStack.push('abracadabra'); + ``` + +- [4.3](#es6-array-spreads) **【必须】** 使用数组展开符 `...` 来拷贝数组。 + + ```javascript + // bad + const len = items.length; + const itemsCopy = []; + let i; + + for (i = 0; i < len; i += 1) { + itemsCopy[i] = items[i]; + } + + // good + const itemsCopy = [...items]; + ``` + +- [4.4](#arrays--from) **【推荐】** 使用展开符 `...` 代替 [`Array.from`](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from),将一个可迭代对象转换成一个数组。 + + ```javascript + const foo = document.querySelectorAll('.foo'); + + // good + const nodes = Array.from(foo); + + // best + const nodes = [...foo]; + ``` + +- [4.5](#arrays--mapping) **【必须】** 使用 [Array.from](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) 将一个类数组(array-like)对象转换成一个数组。 + + ```javascript + const arrLike = { 0: 'foo', 1: 'bar', 2: 'baz', length: 3 }; + + // bad + const arr = Array.prototype.slice.call(arrLike); + + // good + const arr = Array.from(arrLike); + ``` + +- [4.6](#arrays--mapping) **【必须】** 使用 [Array.from](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from) 代替展开符 `...` 映射迭代器,因为它避免了创建一个中间数组。 + + ```javascript + // bad + const baz = [...foo].map(bar); + + // good + const baz = Array.from(foo, bar); + ``` + +- [4.7](#arrays--callback-return) **【推荐】** 在数组回调函数中使用 return 语句。 如果函数体由单个语句的返回表达式组成,并且无副作用,那么可以省略返回值, 具体查看 [8.2](#arrows--implicit-return) 。 eslint: [`array-callback-return`](https://eslint.org/docs/rules/array-callback-return) + + ```javascript + // good + [1, 2, 3].map((x) => { + const y = x + 1; + return x * y; + }); + + // good + [1, 2, 3].map(x => x + 1); + + // bad - 没有返回值,意味着在第一次迭代后 `acc` 没有被定义 + [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { + const flatten = acc.concat(item); + acc[index] = flatten; + }); + + // good + [[0, 1], [2, 3], [4, 5]].reduce((acc, item, index) => { + const flatten = acc.concat(item); + acc[index] = flatten; + return flatten; + }, []); + + // bad + inbox.filter((msg) => { + const { subject, author } = msg; + if (subject === 'Mockingbird') { + return author === 'Harper Lee'; + } else { + return false; + } + }); + + // good + inbox.filter((msg) => { + const { subject, author } = msg; + if (subject === 'Mockingbird') { + return author === 'Harper Lee'; + } + + return false; + }); + ``` + +- [4.8](#arrays--bracket-newline) **【推荐】** 如果数组有多行,则在数组开始括号 `[` 的时候换行,然后在数组结束括号 `]` 的时候换行。 eslint: [`array-bracket-newline`](https://eslint.org/docs/rules/array-bracket-newline) + + ```javascript + // bad + const arr = [ + [0, 1], [2, 3], [4, 5], + ]; + + const objectInArray = [{ + id: 1, + }, { + id: 2, + }]; + + const numberInArray = [ + 1, 2, + ]; + + // good + const arr = [[0, 1], [2, 3], [4, 5]]; + + const objectInArray = [ + { + id: 1, + }, + { + id: 2, + }, + ]; + + const numberInArray = [ + 1, + 2, + ]; + ``` + +## 5. 解构 + +- [5.1](#destructuring--object) **【推荐】** 在访问和使用对象的多个属性时使用对象解构。 eslint: [`prefer-destructuring`](https://eslint.org/docs/rules/prefer-destructuring) + + > 原因? 解构可以避免为这些属性创建临时引用。 + + ```javascript + // bad + function getFullName(user) { + const firstName = user.firstName; + const lastName = user.lastName; + + return `${firstName} ${lastName}`; + } + + // good + function getFullName(user) { + const { firstName, lastName } = user; + return `${firstName} ${lastName}`; + } + + // best + function getFullName({ firstName, lastName }) { + return `${firstName} ${lastName}`; + } + ``` + +- [5.2](#destructuring--array) **【推荐】** 使用数组解构。 eslint: [`prefer-destructuring`](https://eslint.org/docs/rules/prefer-destructuring) + + ```javascript + const arr = [1, 2, 3, 4]; + + // bad + const first = arr[0]; + const second = arr[1]; + + // good + const [first, second] = arr; + ``` + +- [5.3](#destructuring--object-over-array) **【必须】** 在有多个返回值时, 使用对象解构,而不是数组解构。 + + > 原因? 你可以随时添加新的属性或者改变属性的顺序,而不用修改调用方。 + + ```javascript + // bad + function processInput(input) { + // 处理代码... + return [left, right, top, bottom]; + } + + // 调用者需要考虑返回数据的顺序。 + const [left, __, top] = processInput(input); + + // good + function processInput(input) { + // 处理代码... + return { left, right, top, bottom }; + } + + // 调用者只选择他们需要的数据。 + const { left, top } = processInput(input); + ``` + +## 6. 字符 + +- [6.1](#strings--quotes) **【推荐】** 使用单引号 `''` 定义字符串。 eslint: [`quotes`](https://eslint.org/docs/rules/quotes.html) + + ```javascript + // bad + const name = "Capt. Janeway"; + + // bad - 模板文字应该包含插值或换行。 + const name = `Capt. Janeway`; + + // good + const name = 'Capt. Janeway'; + ``` + +- [6.2](#strings--line-length) **【必须】** 不应该用字符串跨行连接符的格式来跨行编写,这样会使当前行长度超过100个字符。 + + > 原因? 断开的字符串维护起来很痛苦,并且会提高索引难度。 + + ```javascript + // bad + const errorMessage = 'This is a super long error that was thrown because \ + of Batman. When you stop to think about how Batman had anything to do \ + with this, you would get nowhere \ + fast.'; + + // bad + const errorMessage = 'This is a super long error that was thrown because ' + + 'of Batman. When you stop to think about how Batman had anything to do ' + + 'with this, you would get nowhere fast.'; + + // good + const errorMessage = 'This is a super long error that was thrown because of Batman. When you stop to think about how Batman had anything to do with this, you would get nowhere fast.'; + ``` + +- [6.3](#es6-template-literals) **【必须】** 构建字符串时,使用字符串模板代替字符串拼接。 eslint: [`prefer-template`](https://eslint.org/docs/rules/prefer-template.html) [`template-curly-spacing`](https://eslint.org/docs/rules/template-curly-spacing) + + > 原因? 字符串模板为您提供了一种可读的、简洁的语法,具有正确的换行和字符串插值特性。 + + ```javascript + // bad + function sayHi(name) { + return 'How are you, ' + name + '?'; + } + + // bad + function sayHi(name) { + return ['How are you, ', name, '?'].join(); + } + + // bad + function sayHi(name) { + return `How are you, ${ name }?`; + } + + // good + function sayHi(name) { + return `How are you, ${name}?`; + } + ``` + +- [6.4](#strings--eval) **【必须】** 永远不要使用 `eval()` 执行放在字符串中的代码,它导致了太多的漏洞。 eslint: [`no-eval`](https://eslint.org/docs/rules/no-eval) + +- [6.5](#strings--escaping) **【必须】** 不要在字符串中转义不必要的字符。 eslint: [`no-useless-escape`](https://eslint.org/docs/rules/no-useless-escape) + + > 原因? 反斜杠损害了可读性,因此只有在必要的时候才可以出现。 + + ```javascript + // bad + const foo = '\'this\' \i\s \"quoted\"'; + + // good + const foo = '\'this\' is "quoted"'; + const foo = `my name is '${name}'`; + ``` + +## 7. 函数 + +- [7.1](#functions--declarations) **【可选】** 使用命名的函数表达式代替函数声明。 eslint: [`func-style`](https://eslint.org/docs/rules/func-style) + + > 原因? 函数声明时作用域被提前了,这意味着在一个文件里函数很容易(太容易了)在其定义之前被引用。这样伤害了代码可读性和可维护性。如果你发现一个函数又大又复杂,并且它干扰了对这个文件其他部分的理解,那么是时候把这个函数单独抽成一个模块了!别忘了给表达式显式的命名,不用管这个名字是不是由一个确定的变量推断出来的(这在现代浏览器和类似babel编译器中很常见)。这消除了由匿名函数在错误调用栈产生的所有假设。 * ([Discussion](https://github.com/airbnb/javascript/issues/794)) + + ```javascript + // bad + function foo() { + // ... + } + + // also good * + const foo = function () { + // ... + }; + + // good + const short = function longUniqueMoreDescriptiveLexicalFoo() { + // ... + }; + ``` + +- [7.2](#functions--iife) **【必须】** 把立即执行函数包裹在圆括号里。 eslint: [`wrap-iife`](https://eslint.org/docs/rules/wrap-iife.html) + + > 原因? 立即调用的函数表达式是个独立的单元 - 将它和它的调用括号还有入参包装在一起可以非常清晰的表明这一点。请注意,在一个到处都是模块的世界中,您几乎用不到 IIFE。 + + ```javascript + // immediately-invoked function expression (IIFE) 立即调用的函数表达式 + (function () { + console.log('Welcome to the Internet. Please follow me.'); + }()); + ``` + +- [7.3](#functions--in-blocks) **【必须】** 切记不要在非功能块中声明函数 (`if`, `while`, 等)。 请将函数赋值给变量。 浏览器允许你这样做, 但是不同浏览器会有不同的行为, 这并不是什么好事。 eslint: [`no-loop-func`](https://eslint.org/docs/rules/no-loop-func.html) + +- [7.4](#functions--note-on-blocks) **【必须】** ECMA-262 将 `block` 定义为语句列表。 而函数声明并不是语句。 + + ```javascript + // bad + if (currentUser) { + function test() { + console.log('Nope.'); + } + } + + // good + let test; + if (currentUser) { + test = () => { + console.log('Yup.'); + }; + } + ``` + +- [7.5](#functions--arguments-shadow) **【必须】** 永远不要给一个参数命名为 `arguments`。 这将会覆盖函数默认的 `arguments` 对象。 eslint: [`no-shadow-restricted-names`](https://eslint.org/docs/rules/no-shadow-restricted-names) + + ```javascript + // bad + function foo(name, options, arguments) { + // ... + } + + // good + function foo(name, options, args) { + // ... + } + ``` + +- [7.6](#es6-rest) **【推荐】** 使用 rest 语法 `...` 代替 `arguments`。 eslint: [`prefer-rest-params`](https://eslint.org/docs/rules/prefer-rest-params) + + > 原因? `...` 明确了你想要拉取什么参数。 而且, rest 参数是一个真正的数组,而不仅仅是类数组的 `arguments` 。 + + ```javascript + // bad + function concatenateAll() { + const args = Array.prototype.slice.call(arguments); + return args.join(''); + } + + // good + function concatenateAll(...args) { + return args.join(''); + } + ``` + +- [7.7](#es6-default-parameters) **【推荐】** 使用默认的参数语法,而不是改变函数参数。 + + ```javascript + // really bad + function handleThings(opts) { + // 不!我们不应该修改参数。 + // 更加错误的是: 如果 opts 是一个 "非正值"(falsy)它将被设置成一个对象 + // 这或许正是你想要的,但它可能会导致一些难以察觉的错误。 + opts = opts || {}; + // ... + } + + // still bad + function handleThings(opts) { + if (opts === void 0) { + opts = {}; + } + // ... + } + + // good + function handleThings(opts = {}) { + // ... + } + ``` + +- [7.8](#functions--default-side-effects) **【必须】** 使用默认参数时避免副作用。 + + > 原因? 他们很容易混淆。 + + ```javascript + var b = 1; + // bad + function count(a = b++) { + console.log(a); + } + count(); // 1 + count(); // 2 + count(3); // 3 + count(); // 3 + ``` + +- [7.9](#functions--defaults-last) **【推荐】** 总是把默认参数放在最后。 eslint: [`default-param-last`](https://eslint.org/docs/rules/default-param-last) + + ```javascript + // bad + function handleThings(opts = {}, name) { + // ... + } + + // good + function handleThings(name, opts = {}) { + // ... + } + ``` + +- [7.10](#functions--constructor) **【推荐】** 永远不要使用函数构造器来创建一个新函数。 eslint: [`no-new-func`](https://eslint.org/docs/rules/no-new-func) + + > 原因? 以这种方式创建一个函数跟 `eval()` 差不多,将会导致漏洞。 + + ```javascript + // bad + var add = new Function('a', 'b', 'return a + b'); + + // still bad + var subtract = Function('a', 'b', 'return a - b'); + ``` + +- [7.11](#functions--signature-spacing) **【必须】** 函数声明语句中需要空格。 eslint: [`space-before-function-paren`](https://eslint.org/docs/rules/space-before-function-paren) [`space-before-blocks`](https://eslint.org/docs/rules/space-before-blocks) + + > 原因? 一致性很好,在删除或添加名称时不需要添加或删除空格。 + + ```javascript + // bad + const f = function(){}; + const g = function (){}; + const h = function() {}; + + // good + const x = function () {}; + const y = function a() {}; + ``` + +- [7.12](#functions--mutate-params) **【推荐】** 不要改变入参。 eslint: [`no-param-reassign`](https://eslint.org/docs/rules/no-param-reassign.html) + + > 原因? 操作入参对象会导致原始调用位置出现意想不到的副作用。 + + ```javascript + // bad + function f1(obj) { + obj.key = 1; + } + + // good + function f2(obj) { + const key = Object.prototype.hasOwnProperty.call(obj, 'key') ? obj.key : 1; + } + ``` + +- [7.13](#functions--reassign-params) **【推荐】** 不要对入参重新赋值,也不要给入参的属性赋值。部分要求修改入参的常用库(如 Koa、Vuex)可以豁免。 eslint: [`no-param-reassign`](https://eslint.org/docs/rules/no-param-reassign.html) + + > 原因? 重新赋值参数会导致意外的行为,尤其是在访问 `arguments` 对象的时候。 它还可能导致性能优化问题,尤其是在 V8 中。 + + ```javascript + // bad + function f1(a) { + a = 1; + // ... + } + + function f2(a) { + if (!a) { a = 1; } + // ... + } + + // good + function f3(a) { + const b = a || 1; + // ... + } + + function f4(a = 1) { + // ... + } + ``` + +- [7.14](#functions--spread-vs-apply) **【推荐】** 优先使用扩展运算符 `...` 来调用可变参数函数。 eslint: [`prefer-spread`](https://eslint.org/docs/rules/prefer-spread) + + > 原因? 它更加清晰,你不需要提供上下文,并且能比用 `apply` 来执行可变参数的 `new` 操作更容易些。 + + ```javascript + // bad + const x = [1, 2, 3, 4, 5]; + console.log.apply(console, x); + + // good + const x = [1, 2, 3, 4, 5]; + console.log(...x); + + // bad + new (Function.prototype.bind.apply(Date, [null, 2016, 8, 5])); + + // good + new Date(...[2016, 8, 5]); + ``` + +- [7.15](#functions--signature-invocation-indentation) **【推荐】** 调用或者书写一个包含多个参数的函数应该像这个指南里的其他多行代码写法一样: 每行值包含一个参数,并且最后一行也要以逗号结尾。eslint: [`function-paren-newline`](https://eslint.org/docs/rules/function-paren-newline) + + ```javascript + // bad + function foo(bar, + baz, + quux) { + // ... + } + + // good + function foo( + bar, + baz, + quux, + ) { + // ... + } + + // bad + console.log(foo, + bar, + baz); + + // good + console.log( + foo, + bar, + baz, + ); + ``` + +## 8. 箭头函数 + +- [8.1](#arrows--use-them) **【推荐】** 当你必须使用匿名函数时 (当传递内联函数时), 使用箭头函数。 eslint: [`prefer-arrow-callback`](https://eslint.org/docs/rules/prefer-arrow-callback.html), [`arrow-spacing`](https://eslint.org/docs/rules/arrow-spacing.html) + + > 原因? 它创建了一个在 `this` 上下文中执行的函数版本,它通常是你想要的,并且是一个更简洁的语法。 + + > 什么时候不适用? 如果你有一个相当复杂的函数,你可能会把这些逻辑转移到它自己的命名函数表达式里。 + + ```javascript + // bad + [1, 2, 3].map(function (x) { + const y = x + 1; + return x * y; + }); + + // good + [1, 2, 3].map((x) => { + const y = x + 1; + return x * y; + }); + ``` + +- [8.2](#arrows--implicit-return) **【推荐】** 如果函数体由一个没有副作用的 [表达式](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators#Expressions) 语句组成,删除大括号和 `return`。否则,保留括号并继续使用 `return` 语句。 eslint: [`arrow-parens`](https://eslint.org/docs/rules/arrow-parens.html), [`arrow-body-style`](https://eslint.org/docs/rules/arrow-body-style.html) + + > 原因? 语法糖。 多个函数被链接在一起时,提高可读性。 + + ```javascript + // bad + [1, 2, 3].map(number => { + const nextNumber = number + 1; + `A string containing the ${nextNumber}.`; + }); + + // good + [1, 2, 3].map(number => `A string containing the ${number + 1}.`); + + // good + [1, 2, 3].map((number) => { + const nextNumber = number + 1; + return `A string containing the ${nextNumber}.`; + }); + + // good + [1, 2, 3].map((number, index) => ({ + [index]: number, + })); + + // 没有副作用的隐式返回 + function foo(callback) { + const val = callback(); + if (val === true) { + // 如果回调返回 true 执行 + } + } + + let bool = false; + + // bad + foo(() => bool = true); + + // good + foo(() => { + bool = true; + }); + ``` + +- [8.3](#arrows--paren-wrap) **【推荐】** 如果表达式跨越多个行,用括号将其括起来,以获得更好的可读性。 + + > 原因? 它清楚地表明了函数的起点和终点。 + +```javascript + // bad + ['get', 'post', 'put'].map(httpMethod => Object.prototype.hasOwnProperty.call( + httpMagicObjectWithAVeryLongName, + httpMethod, + ) + ); + + // good + ['get', 'post', 'put'].map(httpMethod => ( + Object.prototype.hasOwnProperty.call( + httpMagicObjectWithAVeryLongName, + httpMethod, + ) + )); +``` + +- [8.4](#arrows--one-arg-parens) **【推荐】** 如果你的函数只有一个参数并且函数体没有大括号,就删除圆括号。 否则,为了保证清晰和一致性,请给参数加上括号。 注意:总是使用括号是可以接受的,在这种情况下,我们使用 [“always” option](https://eslint.org/docs/rules/arrow-parens#always) 来配置 eslint. eslint: [`arrow-parens`](https://eslint.org/docs/rules/arrow-parens.html) + + > 原因? 让代码看上去不那么乱。 + + ```javascript + // bad + [1, 2, 3].map((x) => x * x); + + // good + [1, 2, 3].map(x => x * x); + + // good + [1, 2, 3].map(number => ( + `A long string with the ${number}. It’s so long that we don’t want it to take up space on the .map line!` + )); + + // bad + [1, 2, 3].map(x => { + const y = x + 1; + return x * y; + }); + + // good + [1, 2, 3].map((x) => { + const y = x + 1; + return x * y; + }); + ``` + +- [8.5](#arrows--confusing) **【推荐】** 避免搞混箭头函数符号 (`=>`) 和比较运算符 (`<=`, `>=`)。 eslint: [`no-confusing-arrow`](https://eslint.org/docs/rules/no-confusing-arrow) + + ```javascript + // bad + const itemHeight = item => item.height > 256 ? item.largeSize : item.smallSize; + + // bad + const itemHeight = (item) => item.height > 256 ? item.largeSize : item.smallSize; + + // good + const itemHeight = item => (item.height > 256 ? item.largeSize : item.smallSize); + + // good + const itemHeight = (item) => { + const { height, largeSize, smallSize } = item; + return height > 256 ? largeSize : smallSize; + }; + ``` + +- [8.6](#whitespace--implicit-arrow-linebreak) **【推荐】** 在箭头函数用隐式 return 时强制将函数体的位置约束在箭头后。 eslint: [`implicit-arrow-linebreak`](https://eslint.org/docs/rules/implicit-arrow-linebreak) + + ```javascript + // bad + (foo) => + bar; + + (foo) => + (bar); + + // good + (foo) => bar; + (foo) => (bar); + (foo) => ( + bar + ); + ``` + +## 9. 类和构造器 + +- [9.1](#constructors--use-class) **【推荐】** 尽量使用 `class`. 避免直接操作 `prototype` . + + > 原因? `class` 语法更简洁,更容易看懂。 + + ```javascript + // bad + function Queue(contents = []) { + this.queue = [...contents]; + } + Queue.prototype.pop = function () { + const value = this.queue[0]; + this.queue.splice(0, 1); + return value; + }; + + // good + class Queue { + constructor(contents = []) { + this.queue = [...contents]; + } + pop() { + const value = this.queue[0]; + this.queue.splice(0, 1); + return value; + } + } + ``` + +- [9.2](#constructors--extends) **【推荐】** 使用 `extends` 来实现继承。 + + > 原因? 它是一个内置的方法,可以在不破坏 `instanceof` 的情况下继承原型功能。 + + ```javascript + // bad + const inherits = require('inherits'); + function PeekableQueue(contents) { + Queue.apply(this, contents); + } + inherits(PeekableQueue, Queue); + PeekableQueue.prototype.peek = function () { + return this.queue[0]; + }; + + // good + class PeekableQueue extends Queue { + peek() { + return this.queue[0]; + } + } + ``` + +- [9.3](#constructors--chaining) **【可选】** 类的成员方法,可以返回 `this`, 来实现链式调用。 + + ```javascript + // bad + Jedi.prototype.jump = function () { + this.jumping = true; + return true; + }; + + Jedi.prototype.setHeight = function (height) { + this.height = height; + }; + + const luke = new Jedi(); + luke.jump(); // => true + luke.setHeight(20); // => undefined + + // good + class Jedi { + jump() { + this.jumping = true; + return this; + } + + setHeight(height) { + this.height = height; + return this; + } + } + + const luke = new Jedi(); + + luke.jump() + .setHeight(20); + ``` + +- [9.4](#constructors--tostring) **【可选】** 只要在确保能正常工作并且不产生任何副作用的情况下,编写一个自定义的 `toString()` 方法也是可以的。 + + ```javascript + class Jedi { + constructor(options = {}) { + this.name = options.name || 'no name'; + } + + getName() { + return this.name; + } + + toString() { + return `Jedi - ${this.getName()}`; + } + } + ``` + +- [9.5](#constructors--no-useless) **【推荐】** 如果没有具体说明,类有默认的构造方法。一个空的构造函数或只是代表父类的构造函数是不需要写的。 eslint: [`no-useless-constructor`](https://eslint.org/docs/rules/no-useless-constructor) + + ```javascript + // bad + class Jedi { + constructor() {} + + getName() { + return this.name; + } + } + + // bad + class Rey extends Jedi { + // 这种构造函数是不需要写的 + constructor(...args) { + super(...args); + } + } + + // good + class Rey extends Jedi { + constructor(...args) { + super(...args); + this.name = 'Rey'; + } + } + ``` + +- [9.6](#classes--no-duplicate-members) **【必须】** 避免定义重复的类成员。 eslint: [`no-dupe-class-members`](https://eslint.org/docs/rules/no-dupe-class-members) + + > 原因? 重复的类成员声明将会默认使用最后一个 - 具有重复的类成员可以说是一个bug。 + + ```javascript + // bad + class Foo { + bar() { return 1; } + bar() { return 2; } + } + + // good + class Foo { + bar() { return 1; } + } + + ``` + +- [9.7] **【推荐】** 类成员要么引用 `this` ,要么声明为静态方法,除非一个外部库或框架需要使用某些非静态方法。当一个方法为非静态方法时,一般表明它在不同的实例上会表现得不同。 + +## 10. 模块 + +- [10.1](#modules--use-them) **【可选】** 使用ES6的模块 (`import`/`export`) 语法来定义模块。 + + ```javascript + // bad + const AirbnbStyleGuide = require('./AirbnbStyleGuide'); + module.exports = AirbnbStyleGuide.es6; + + // ok + import AirbnbStyleGuide from './AirbnbStyleGuide'; + export default AirbnbStyleGuide.es6; + + // best + import { es6 } from './AirbnbStyleGuide'; + export default es6; + ``` + +- [10.2](#modules--no-wildcard) **【推荐】** 不要使用import * 通配符 + + > 原因? 这确保你有单个默认的导出。 + + ```javascript + // bad + import * as AirbnbStyleGuide from './AirbnbStyleGuide'; + + // good + import AirbnbStyleGuide from './AirbnbStyleGuide'; + ``` + +- [10.3](#modules--no-export-from-import) **【推荐】** 不要在import语句中直接export。 + + > 原因? 虽然写在一行很简洁,但是有一个明确的导入和一个明确的导出能够保证一致性。 + + ```javascript + // bad + // filename es6.js + export { es6 as default } from './AirbnbStyleGuide'; + + // good + // filename es6.js + import { es6 } from './AirbnbStyleGuide'; + export default es6; + ``` + +- [10.4](#import/no-duplicates) **【必须】** 对于同一个路径,只在一个地方引入所有需要的东西。 + eslint: [`no-duplicates`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-duplicates.md) + + > 原因? 对于同一个路径,如果存在多行引入,会使代码更难以维护。 + + ```javascript + // bad + import foo from 'foo'; + // … 其他导入 … // + import { named1, named2 } from 'foo'; + + // good + import foo, { named1, named2 } from 'foo'; + + // good + import foo, { + named1, + named2, + } from 'foo'; + ``` + +- [10.5](#modules--no-mutable-exports) **【推荐】** 不要导出可变的引用。 + eslint: [`import/no-mutable-exports`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-mutable-exports.md) + + > 原因? 在一般情况下,应该避免导出可变引用。虽然在某些特殊情况下,可能需要这样,但是一般情况下只需要导出常量引用。 + + ```javascript + // bad + let foo = 3; + export { foo }; + + // good + const foo = 3; + export { foo }; + ``` + +- [10.6](#modules--prefer-default-export) **【可选】** 在只有单一导出的模块里,用 export default 更好。 + eslint: [`import/prefer-default-export`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/prefer-default-export.md) + + > 原因? 鼓励更多的模块只做单一导出,会增强代码的可读性和可维护性。 + + ```javascript + // bad + export function foo() {} + + // good + export default function foo() {} + ``` + +- [10.7](#modules--imports-first) **【必须】** 将所有的 `import`s 语句放在其他语句之前。 + eslint: [`import/first`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/first.md) + + > 原因? 将所有的 `import`s 提到顶部,可以防止某些诡异行为的发生。 + + ```javascript + // bad + import foo from 'foo'; + foo.init(); + + import bar from 'bar'; + + // good + import foo from 'foo'; + import bar from 'bar'; + + foo.init(); + ``` + +- [10.8](#modules--multiline-imports-over-newlines) **【可选】** 多行引入应该像多行数组和对象字面量一样缩进。 + + > 原因? 这里的花括号和其他地方的花括号是一样的,遵循相同的缩进规则。末尾的逗号也是一样的。 + + ```javascript + // bad + import {longNameA, longNameB, longNameC, longNameD, longNameE} from 'path'; + + // good + import { + longNameA, + longNameB, + longNameC, + longNameD, + longNameE, + } from 'path'; + ``` + +- [10.9](#modules--no-webpack-loader-syntax) **【推荐】** 在模块导入语句中禁止使用 Webpack 加载器语法。 + eslint: [`import/no-webpack-loader-syntax`](https://github.com/benmosher/eslint-plugin-import/blob/master/docs/rules/no-webpack-loader-syntax.md) + + > 原因? 因为在导入语句中使用 webpack 语法,会将代码和打包工具耦合在一起。应该在 `webpack.config.js` 中使用加载器语法。 + + ```javascript + // bad + import fooSass from 'css!sass!foo.scss'; + import barCss from 'style!css!bar.css'; + + // good + import fooSass from 'foo.scss'; + import barCss from 'bar.css'; + ``` + +## 11. 迭代器和发生器 + +- [11.1](#iterators--nope) **【推荐】** 不要使用迭代器。 推荐使用 JavaScript 的高阶函数代替 `for-in` 。 eslint: [`no-iterator`](https://eslint.org/docs/rules/no-iterator.html) [`no-restricted-syntax`](https://eslint.org/docs/rules/no-restricted-syntax) + + > 原因? 这有助于不可变性原则。 使用带有返回值的纯函数比使用那些带有副作用的方法,更具有可读性。 + + > 使用 `map()` / `every()` / `filter()` / `find()` / `findIndex()` / `reduce()` / `some()` / ... 遍历数组, 和使用 `Object.keys()` / `Object.values()` / `Object.entries()` 迭代你的对象生成数组。 + + ```javascript + const numbers = [1, 2, 3, 4, 5]; + + // bad + let sum = 0; + for (let num of numbers) { + sum += num; + } + sum === 15; + + // good + let sum = 0; + numbers.forEach((num) => { + sum += num; + }); + sum === 15; + + // best (use the functional force) + const sum = numbers.reduce((total, num) => total + num, 0); + sum === 15; + + // bad + const increasedByOne = []; + for (let i = 0; i < numbers.length; i++) { + increasedByOne.push(numbers[i] + 1); + } + + // good + const increasedByOne = []; + numbers.forEach((num) => { + increasedByOne.push(num + 1); + }); + + // best (keeping it functional) + const increasedByOne = numbers.map(num => num + 1); + ``` + +- [11.2](#generators--nope) **【可选】** 现在不要使用generator。 + + > 原因? 它们不能很好的转译为 ES5。但可以在Nodejs中使用。* + +- [11.3](#generators--spacing) **【推荐】** 如果你必须要使用generator,请确保正确使用空格。 eslint: [`generator-star-spacing`](https://eslint.org/docs/rules/generator-star-spacing) + + > 原因? `function` 和 `*` 是同一个概念关键字的一部分 - `*` 不是 `function` 的修饰符, `function*` 是一个不同于 `function` 的构造器。 + + ```javascript + // bad + function * foo() { + // ... + } + + // bad + const bar = function * () { + // ... + }; + + // bad + const baz = function *() { + // ... + }; + + // bad + const quux = function*() { + // ... + }; + + // bad + function*foo() { + // ... + } + + // bad + function *foo() { + // ... + } + + // very bad + function + * + foo() { + // ... + } + + // very bad + const wat = function + * + () { + // ... + }; + + // good + function* foo() { + // ... + } + + // good + const foo = function* () { + // ... + }; + ``` + +## 12. 属性 + +- [12.1](#properties--dot) **【推荐】** 访问属性时使用点符号。 eslint: [`dot-notation`](https://eslint.org/docs/rules/dot-notation.html) + + ```javascript + const luke = { + jedi: true, + age: 28, + }; + + // bad + const isJedi = luke['jedi']; + + // good + const isJedi = luke.jedi; + ``` + +- [12.2](#properties--bracket) **【可选】** 使用变量访问属性时,用 `[]`表示法。 + + ```javascript + const luke = { + jedi: true, + age: 28, + }; + + function getProp(prop) { + return luke[prop]; + } + + const isJedi = getProp('jedi'); + ``` + +- [12.3](#es2016-properties--exponentiation-operator) **【推荐】** 计算指数时,可以使用 `**` 运算符。 eslint: [`no-restricted-properties`](https://eslint.org/docs/rules/no-restricted-properties). + + ```javascript + // bad + const binary = Math.pow(2, 10); + + // good + const binary = 2 ** 10; + ``` + +## 13. 变量 + +- [13.1](#variables--const) **【必须】** 变量应先声明再使用,禁止引用任何未声明的变量,除非你明确知道引用的变量存在于当前作用域链上。禁止不带任何关键词定义变量,这样做将会创建一个全局变量,污染全局命名空间,造成程序意料之外的错误。 eslint: [`no-undef`](https://eslint.org/docs/rules/no-undef) [`prefer-const`](https://eslint.org/docs/rules/prefer-const) + + ```javascript + // bad, 这会创建一个全局变量 + superPower = new SuperPower(); + + // good + const superPower = new SuperPower(); + + // bad, 容易污染外部变量 + let superPower = 'a'; + (function() { + superPower = 'b'; + })(); + console.log(superPower); + + // good + let superPower = 'a'; + (function() { + let superPower = 'b'; + })(); + console.log(superPower); + + // bad, 更常见的情况是这样的,在 for 循环里的 i 将会污染外部的变量 i + let i = 1; + (function() { + for (i = 0; i < 10; i++) { + console.log('inside', i); + } + + console.log('outside', i) + })(); + console.log('global', i); + + // good + let i = 1; + (function() { + // i 的作用域在 for 循环内 + for (let i = 0; i < 10; i++) { + console.log('inside i', i); + } + + // 如果真的需要在 for 循环外使用循环变量,应该先定义在外部 + let j; + + for (j = 0; j < 10; j++) { + console.log('inside j:', j); + } + + console.log('outside j', j); + })(); + console.log('global', i); + ``` + +- [13.2](#variables--one-const) **【推荐】** 声明多个变量应该分开声明,避免使用 `,` 一次声明多个变量。 eslint: [`one-var`](https://eslint.org/docs/rules/one-var.html) + + > 原因? 这样更容易添加新的变量声明,不必担心是使用 `;` 还是使用 `,` 所带来的代码差异。使用版本管理工具如 git ,最后那行的 `;` 就不会被标记为修改成 `,`。 并且可以通过 debugger 逐步查看每个声明,而不是立即跳过所有声明。 + + ```javascript + // bad + const items = getItems(), + goSportsTeam = true, + dragonball = 'z'; + + // bad + const items = getItems(), + goSportsTeam = true; + // 定义成了全局变量 + dragonball = 'z'; + + // good + const items = getItems(); + const goSportsTeam = true; + const dragonball = 'z'; + ``` + +- [13.3](#variables--const-let-group) **【推荐】** 把 `const` 声明语句放在一起,把 `let` 声明语句放在一起。 + + > 原因? 这在后边如果需要根据前边的赋值变量指定一个变量时很有用,且更容易知道哪些变量是不希望被修改的。 + + ```javascript + // bad + let i; + const items = getItems(); + let dragonball; + const goSportsTeam = true; + let len; + + // good + const goSportsTeam = true; + const items = getItems(); + let dragonball; + let i; + let length; + ``` + +- [13.4](#variables--define-where-used) **【推荐】** 在你真正需要使用到变量的代码块内定义变量。 + + > 原因? `let` 和 `const` 是块级作用域而不是函数作用域,不存在变量提升的情况。 + + ```javascript + // bad, 不必要的函数调用 + function checkName(hasName) { + const name = getName(); + + if (hasName === 'test') { + return false; + } + + if (name === 'test') { + this.setName(''); + return false; + } + + return name; + } + + // good + function checkName(hasName) { + if (hasName === 'test') { + return false; + } + + const name = getName(); + + if (name === 'test') { + this.setName(''); + return false; + } + + return name; + } + ``` + +- [13.5](#variables--no-chain-assignment) **【必须】** 不要链式变量赋值。 eslint: [`no-multi-assign`](https://eslint.org/docs/rules/no-multi-assign) + + > 原因? 链式变量赋值会创建隐式全局变量。 + + ```javascript + // bad + (function example() { + /* + * JavaScript 把它解释为 + * let a = ( b = ( c = 1 ) ); + * let 关键词只适用于变量 a,变量 b 和变量 c 则变成了全局变量。 + */ + let a = b = c = 1; + }()); + + // throws ReferenceError + console.log(a); + // 1 + console.log(b); + // 1 + console.log(c); + + // good + (function example() { + let a = 1; + let b = a; + let c = a; + }()); + + // throws ReferenceError + console.log(a); + // throws ReferenceError + console.log(b); + // throws ReferenceError + console.log(c); + + // 对于 `const` 也一样 + ``` + +- [13.6](#variables--unary-increment-decrement) **【必须】** 避免使用不必要的递增和递减操作符 (`++`, `--`)。 eslint [`no-plusplus`](https://eslint.org/docs/rules/no-plusplus) + + > 原因? 在eslint文档中,一元操作符 `++` 和 `--`会自动添加分号,不同的空白可能会改变源代码的语义。建议使用 `num += 1` 这样的语句来做递增和递减,而不是使用 `num++` 或 `num ++` 。同时 `++num` 和 `num++` 的差异也使代码的可读性变差。不必要的增量和减量语句会导致无法预先明确递增/预递减值,这可能会导致程序中的意外行为。 + + > 但目前依然允许在 for loop 中使用 `++`、`--` 的语法,但依然建议尽快迁移到 `+= 1`、`-= 1` 的语法。 [#22](https://git.woa.com/standards/javascript/issues/22) + + ```javascript + // bad, i = 11, j = 20 + let i = 10; + let j = 20; + i ++ + j + + // bad, i = 10, j = 21 + let i = 10; + let j = 20; + i + ++ + j + + // bad + const array = [1, 2, 3]; + let num = 1; + num++; + --num; + + // not good, just acceptable for upforward compatible. + let sum = 0; + let truthyCount = 0; + for (let i = 0; i < array.length; i++) { + let value = array[i]; + sum += value; + if (value) { + truthyCount++; + } + } + + // good + const array = [1, 2, 3]; + let num = 1; + num += 1; + num -= 1; + + // good + const sum = array.reduce((a, b) => a + b, 0); + const truthyCount = array.filter(Boolean).length; + ``` + +- [13.7](#variables--linebreak) **【必须】** 避免在赋值语句 `=` 前后换行。如果你的代码单行长度超过了 [`max-len`](https://eslint.org/docs/rules/max-len.html) 定义的长度而不得不换行,那么使用括号包裹。 eslint [`operator-linebreak`](https://eslint.org/docs/rules/operator-linebreak.html). + + > 原因? 在 `=` 前后换行,可能混淆赋的值。 + + ```javascript + // bad + const foo + = 'superLongLongLongLongLongLongLongLongString'; + + // bad + const bar = + superLongLongLongLongLongLongLongLongFunctionName(); + + // bad + const fullHeight = borderTop + + innerHeight + + borderBottom; + + // bad + const anotherHeight = borderTop + + innerHeight + + borderBottom; + + // bad + const thirdHeight = ( + borderTop + + innerHeight + + borderBottom + ); + + // good - max-len 会忽略字符串,直接写后面即可。 + const foo = 'superLongLongLongLongLongLongLongLongString'; + + // good + const bar = ( + superLongLongLongLongLongLongLongLongFunctionName() + ); + + // good + const fullHeight = borderTop + + innerHeight + + borderBottom; + + // good + const anotherHeight = borderTop + + innerHeight + + borderBottom; + + // good + const thirdHeight = ( + borderTop + + innerHeight + + borderBottom + ); + + ``` + +- [13.8](#variables--no-unused-vars) **【必须】** 禁止定义了变量却不使用它。 eslint: [`no-unused-vars`](https://eslint.org/docs/rules/no-unused-vars) + + > 原因? 在代码里到处定义变量却没有使用它,不完整的代码结构看起来像是个代码错误。即使没有使用,但是定义变量仍然需要消耗资源,并且对阅读代码的人也会造成困惑,不知道这些变量是要做什么的。 + + ```javascript + // bad + let some_unused_var = 42; + + // bad,定义了变量不意味着就是使用了 + let y = 10; + y = 5; + + // bad,对自身的操作并不意味着使用了 + let z = 0; + z = z + 1; + + // bad, 未使用的函数参数 + function getX(x, y) { + return x; + } + + // good + function getXPlusY(x, y) { + return x + y; + } + + let x = 1; + let y = a + 2; + + alert(getXPlusY(x, y)); + + /* + * 有时候我们想要提取某个对象排除了某个属性外的其他属性,会用 rest 参数解构对象 + * 这时候 type 虽然未使用,但是仍然被定义和赋值,这也是一种空间的浪费 + * type 的值是 'a' + * coords 的值是 data 对象,但是没有 type 属性 { example1: 'b', example2: 'c' } + */ + let data = { type: 'a', example1: 'b', example2: 'c' } + let { type, ...coords } = data; + + /* + * 有时候如果定义了一个基类或者接口(Typescript) + * 基类或接口中该方法需要定义这个参数,但消费参数是由子类自行实现的 + * 可以通过在变量名前加下划线的方式来表示该变量是未使用的 + */ + export class Model { + toList(_isCompact) { + // 待子类实现 + } + } + + export class MyModel extends Model { + data = []; + toList(isCompact) { + return isCompact ? this.data.flat() : this.data; + } + } + ``` + +## 14. 变量提升 + +- [14.1](#hoisting--about) **【可选】** `var` 定义的变量会被提升到函数作用域范围内的最顶部,但是对它的赋值是不会被提升的,因此在函数顶部相当于定义了变量,但是值是 `undefined`。`const` 和 `let` 声明的变量受到一个称之为 "暂时性死区" [(Temporal Dead Zones ,简称 TDZ)](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let#Temporal_dead_zone) 的新概念保护,因此在 "暂时性死区" 内部的 `const` 和 `let` 变量,都需要先声明再使用,否则会报错。详情可以阅读 [typeof 不再安全](https://web.archive.org/web/20200121061528/http://es-discourse.com/t/why-typeof-is-no-longer-safe/15) 这篇文章。 + + ```javascript + // notDefined 未定义 (假设没有定义的同名全局变量) + function example() { + // => throws a ReferenceError + console.log(notDefined); + } + + /* + * 函数体内部因存在 var 变量声明,因此在引用变量的语句之前,变量提升就已经起作用了 + * 注意: 真正的值 `true` 不会被提升。 + */ + function example() { + // => undefined + console.log(declaredButNotAssigned); + var declaredButNotAssigned = true; + } + + /* + * 解释器将变量提升到函数的顶部 + * 这意味着我们可以将上边的例子重写为: + */ + function example() { + let declaredButNotAssigned; + // => undefined + console.log(declaredButNotAssigned); + declaredButNotAssigned = true; + } + + // 使用 const 和 let + function example() { + // => throws a ReferenceError + console.log(declaredButNotAssigned); + // => throws a ReferenceError + console.log(typeof declaredButNotAssigned); + const declaredButNotAssigned = true; + } + ``` + +- [14.2](#hoisting--anon-expressions) **【可选】** 匿名函数赋值表达式提升变量名,而不是函数赋值。 + + ```javascript + function example() { + // => undefined + console.log(anonymous); + + // => TypeError anonymous is not a function + anonymous(); + + var anonymous = function () { + console.log('anonymous function expression'); + }; + } + ``` + +- [14.3](#hoisting--named-expressions) **【可选】** 命名函数表达式提升的是变量名,而不是函数名或者函数体。 + + ```javascript + function example() { + // => undefined + console.log(named); + + // => TypeError named is not a function + named(); + + // => ReferenceError superPower is not defined + superPower(); + + var named = function superPower() { + console.log('Flying'); + }; + } + + // 当函数名和变量名相同时也是如此。 + function example() { + // => undefined + console.log(named); + + // => TypeError named is not a function + named(); + + var named = function named() { + console.log('named'); + }; + } + ``` + +- [14.4](#hoisting--declarations) **【可选】** 函数声明提升其名称和函数体。 + + ```javascript + function example() { + // => Flying + superPower(); + + function superPower() { + console.log('Flying'); + } + } + ``` + + - 更多信息请参考 [Ben Cherry](http://www.adequatelygood.com/) 的 [JavaScript Scoping & Hoisting](http://www.adequatelygood.com/2010/2/JavaScript-Scoping-and-Hoisting/)。 + +## 15. 比较运算符和等号 + +- [15.1](#comparison--eqeqeq) **【推荐】** 使用 `===` 和 `!==` 而不是 `==` 和 `!=`。 eslint: [`eqeqeq`](https://eslint.org/docs/rules/eqeqeq.html) + + > 原因?`==` 和 `!=` 存在类型转换,会得到和 `===`、`!==` 不一样的结果 + + ```javascript + // bad, true + undefined == null + // good, false + undefined === null + + // bad, true + '0' == 0 + // good, false + '0' === 0 + + // bad, true + 0 == false + // good, false + 0 === false + + // bad, true + '' == false + // good, false + '' === false + ``` + +- [15.2](#comparison--if) **【可选】** 条件语句,例如 `if` 语句使用 `ToBoolean` 的抽象方法来计算表达式的结果,并始终遵循以下简单的规则: + + - **Objects** 的取值为: **true**,{} 和 [] 的取值也为: **true** + - **Undefined** 的取值为: **false** + - **Null** 的取值为: **false** + - **Booleans** 的取值为: **布尔值的取值** + - **Numbers** 的取值为:如果为 **+0, -0, or NaN** 值为 **false** 否则为 **true** + - **Strings** 的取值为: 如果是一个空字符串 `''` 值为 **false** 否则为 **true** + + ```javascript + if ([0] && []) { + // true, 数组(即使是空的)是一个对象,对象的取值为 true + } + ``` + +- [15.3](#comparison--shortcuts) **【推荐】** 对于布尔值(在明确知道是布尔值的情况下)使用简写,但是对于字符串和数字进行显式比较。 + + ```javascript + // bad + if (isValid === true) { + // ... + } + + // good + if (isValid) { + // ... + } + + // bad + if (name) { + // ... + } + + // good + if (name !== '') { + // ... + } + + // bad + if (collection.length) { + // ... + } + + // good + if (collection.length > 0) { + // ... + } + ``` + +- [15.4](#comparison--moreinfo) **【可选】** 关于布尔值转换和条件语句,详细信息可参阅 Angus Croll 的 [Truth Equality and JavaScript](https://javascriptweblog.wordpress.com/2011/02/07/truth-equality-and-javascript/#more-2108) 这篇文章。 + +- [15.5](#comparison--switch-blocks) **【必须】** 在 `case` 和 `default` 的子句中,如果存在声明 (例如. `let`, `const`, `function`, 和 `class`),使用大括号来创建块级作用域。 eslint: [`no-case-declarations`](https://eslint.org/docs/rules/no-case-declarations.html) + + > 原因? 变量声明的作用域在整个 switch 语句内,但是只有在 case 条件为真时变量才会被初始化。 当多个 `case` 语句定义相同的变量时,就会导致变量覆盖的问题。 + + ```javascript + // bad + switch (foo) { + case 1: + let x = 1; + break; + case 2: + const y = 2; + break; + case 3: + function f() { + // ... + } + break; + default: + class C {} + } + + // good + switch (foo) { + case 1: { + let x = 1; + break; + } + case 2: { + const y = 2; + break; + } + case 3: { + function f() { + // ... + } + break; + } + case 4: + bar(); + break; + default: { + class C {} + } + } + ``` + +- [15.6](#comparison--nested-ternaries) **【推荐】** 三元表达式不应该嵌套,通常是单行表达式,如果确实需要多行表达式,那么应该考虑使用条件语句。 eslint: [`no-nested-ternary`](https://eslint.org/docs/rules/no-nested-ternary.html) + + ```javascript + // bad + const foo = maybe1 > maybe2 + ? "bar" + : value1 > value2 ? "baz" : null; + + // 分离为两个三元表达式 + const maybeNull = value1 > value2 ? 'baz' : null; + + // better + const foo = maybe1 > maybe2 + ? 'bar' + : maybeNull; + + // best + const foo = maybe1 > maybe2 ? 'bar' : maybeNull; + ``` + +- [15.7](#comparison--unneeded-ternary) **【推荐】** 避免不必要的三元表达式。 eslint: [`no-unneeded-ternary`](https://eslint.org/docs/rules/no-unneeded-ternary.html) + + ```javascript + // bad + const foo = a ? a : b; + const bar = c ? true : false; + const baz = c ? false : true; + + // good + const foo = a || b; + const bar = !!c; + const baz = !c; + ``` + +- [15.8](#comparison--no-mixed-operators) **【必须】** 使用混合运算符时,使用小括号括起来需要一起计算的部分,只要觉得有必要,那么尽可能地用括号让代码的优先级更明显。大家都能理解的运算符 `+`、`-`、`**` 不要求添加括号。但我们建议在 `*`、`/` 之间添加括号,因为乘除运算符混写写的比较长的时候容易产生歧义。 eslint: [`no-mixed-operators`](https://eslint.org/docs/rules/no-mixed-operators.html) + + > 原因? 这能提高可读性并且表明开发人员的意图。 + + ```javascript + // bad + const foo = a && b < 0 || c > 0 || d + 1 === 0; + + // bad + const bar = a ** b - 5 % d; + + // bad, 可能陷入一种 (a || b) && c 的思考 + if (a || b && c) { + return d; + } + + // bad + const bar1 = a + b / c * (d / e); + + // good + const foo = (a && b < 0) || (c > 0) || (d + 1 === 0); + + // good + const bar = (a ** b) - (5 % d); + + // good + if (a || (b && c)) { + return d; + } + + // good + const bar1 = a + (b / c) * (d / e); + ``` + +## 16. 代码块 + +- [16.1](#blocks--braces) **【必须】** 当有多行代码块的时候,应使用大括号包裹。 eslint: [`nonblock-statement-body-position`](https://eslint.org/docs/rules/nonblock-statement-body-position) + + ```javascript + // bad + if (test) + return false; + + // bad + let condition = true; + let test = 1; + // 在缩进不规范的时候,容易造成误解 + if (condition) + condition = false; + test = 2; + + // good + if (test) return false; + + // good + if (test) { + return false; + } + + // bad + function foo() { return false; } + + // good + function bar() { + return false; + } + ``` + +- [16.2](#blocks--cuddled-elses) **【必须】** 如果你使用的是 `if` 和 `else` 的多行代码块,则将 `else` 语句放在 `if` 块闭括号同一行的位置。 eslint: [`brace-style`](https://eslint.org/docs/rules/brace-style.html) + + ```javascript + // bad + if (test) { + thing1(); + thing2(); + } + else { + thing3(); + } + + // good + if (test) { + thing1(); + thing2(); + } else { + thing3(); + } + ``` + +- [16.3](#blocks--no-else-return) **【推荐】** 如果一个 `if` 块总是会执行 return 语句,那么接下来的 `else` 块就没有必要了。 如果一个包含 `return` 语句的 `else if` 块,在一个包含了 `return` 语句的 `if` 块之后,那么可以拆成多个 `if` 块。 eslint: [`no-else-return`](https://eslint.org/docs/rules/no-else-return) + + ```javascript + // bad + function foo() { + if (x) { + return x; + } else { + return y; + } + } + + // bad + function cats() { + if (x) { + return x; + } else if (y) { + return y; + } + } + + // bad + function dogs() { + if (x) { + return x; + } else { + if (y) { + return y; + } + } + } + + // good + function foo() { + if (x) { + return x; + } + + return y; + } + + // good + function cats() { + if (x) { + return x; + } + + if (y) { + return y; + } + } + + // good + function dogs(x) { + if (x) { + if (z) { + return y; + } + } else { + return z; + } + } + ``` + +## 17. 控制语句 + +- [17.1](#control-statements) **【推荐】** 如果你的控制语句 (`if`, `while` 等) 太长或者超过了一行最大长度的限制,则可以将每个条件(或组)放入一个新的行。 逻辑运算符应该在行的开始。 + + > 原因? 在行的开头要求运算符保持对齐,并遵循类似于方法链的模式。这提高了可读性,并且使更复杂的逻辑更容易直观的被理解。 + + ```javascript + // bad + if ((foo === 123 || bar === 'abc') && doesItLookGoodWhenItBecomesThatLong() && isThisReallyHappening()) { + thing1(); + } + + // bad + if (foo === 123 && + bar === 'abc') { + thing1(); + } + + // bad + if (foo === 123 + && bar === 'abc') { + thing1(); + } + + // bad + if ( + foo === 123 && + bar === 'abc' + ) { + thing1(); + } + + // good + if ( + foo === 123 + && bar === 'abc' + ) { + thing1(); + } + + // good + if ( + (foo === 123 || bar === 'abc') + && doesItLookGoodWhenItBecomesThatLong() + && isThisReallyHappening() + ) { + thing1(); + } + + // good + if (foo === 123 && bar === 'abc') { + thing1(); + } + ``` + +- [17.2](#control-statements--value-selection) **【必须】** 不要使用选择操作符代替控制语句。 + + ```javascript + // bad + !isRunning && startRunning(); + + // good + if (!isRunning) { + startRunning(); + } + ``` + +## 18. 注释 + +- [18.1](#comments--multiline) **【必须】** 使用 `/* ... */` 来进行多行注释。 + + ```javascript + // bad + // make() returns a new element + // based on the passed in tag name + // + // @param {String} tag + // @return {Element} element + function make(tag) { + + // ... + + return element; + } + + // good + /* + * make() returns a new element + * based on the passed-in tag name + */ + function make(tag) { + + // ... + + return element; + } + ``` + +- [18.2](#comments--singleline) **【推荐】** 使用 `//` 进行单行注释。 将单行注释放在需要注释的行的上方新行。 建议在注释之前放一个空行,除非它在块的第一行。但如果一段代码每行都包含注释,允许不加分行。 + + ```javascript + // bad + const active = true; // is current tab + + // good + // is current tab + const active = true; + + // bad + function getType() { + console.log('fetching type...'); + // set the default type to 'no type' + const type = this.type || 'no type'; + + return type; + } + + // good + function getType() { + console.log('fetching type...'); + + // set the default type to 'no type' + const type = this.type || 'no type'; + + return type; + } + + // also good + function getType() { + // set the default type to 'no type' + const type = this.type || 'no type'; + + return type; + } + ``` + +- [18.3](#comments--spaces) **【必须】** 用一个空格开始所有的注释,使它更容易阅读。 eslint: [`spaced-comment`](https://eslint.org/docs/rules/spaced-comment) + + ```javascript + // bad + //is current tab + const active = true; + + // good + // is current tab + const active = true; + + // bad + /** + *make() returns a new element + *based on the passed-in tag name + */ + function make(tag) { + + // ... + + return element; + } + + // good + /** + * make() returns a new element + * based on the passed-in tag name + */ + function make(tag) { + + // ... + + return element; + } + ``` + +- [18.4](#comments--actionitems) **【推荐】** 使用 `FIXME` 或者 `TODO` 开始你的注释可以帮助其他开发人员快速了解相应代码,如果你提出了一个需要重新讨论的问题,或者你对需要解决的问题提出的解决方案。 这些不同于其他普通注释,因为它们是可操作的。 这些操作是 `FIXME: -- 需要解决这个问题` 或者 `TODO: -- 需要被实现`。 + +- [18.5](#comments--fixme) **【推荐】** 使用 `// FIXME:` 注释问题。 + + ```javascript + class Calculator extends Abacus { + constructor() { + super(); + + // FIXME: 这里不应该使用全局变量 + total = 0; + } + } + ``` + +- [18.6](#comments--todo) **【推荐】** 使用 `// TODO:` 注释解决问题的方法。 + + ```javascript + class Calculator extends Abacus { + constructor() { + super(); + + // TODO: total 应该由一个 param 的选项配置 + this.total = 0; + } + } + ``` + +- [18.7](#comments--jsdoc) **【必须】** `/** ... */` 风格(首行有两个 *)的块级多行注释仅能被用于 JSDoc。 + + ```javascript + class Calculator { + /** + * 用于将多个数字相加求和 + * + * @param {number[]} nums 一系列用于相加的数字 + * @returns {number} 最终的和 + */ + add(...nums) { + return nums.reduce((res, num) => res + num, 0); + } + } + ``` + +## 19. 空白 + +- [19.1](#whitespace--spaces) **【推荐】** 使用 tabs (空格字符) 设置为2个空格。 eslint: [`indent`](https://eslint.org/docs/rules/indent.html) + + ```javascript + // bad + function foo() { + ∙∙∙∙let name; + } + + // bad + function bar() { + ∙let name; + } + + // good + function baz() { + ∙∙let name; + } + ``` + +- [19.2](#whitespace--before-blocks) **【必须】** 在花括号前放置一个空格。 eslint: [`space-before-blocks`](https://eslint.org/docs/rules/space-before-blocks.html) + + ```javascript + // bad + function test(){ + console.log('test'); + } + + // good + function test() { + console.log('test'); + } + + // bad + dog.set('attr',{ + age: '1 year', + breed: 'Bernese Mountain Dog', + }); + + // good + dog.set('attr', { + age: '1 year', + breed: 'Bernese Mountain Dog', + }); + ``` + +- [19.3](#whitespace--around-keywords) **【必须】** 在控制语句中的左括号前放置1个空格(if,while等)。在函数调用和声明中,参数列表和函数名之间不能留空格。[`keyword-spacing`](https://eslint.org/docs/rules/keyword-spacing.html) + + ```javascript + // bad + if(isJedi) { + fight (); + } + + // good + if (isJedi) { + fight(); + } + + // bad + function fight () { + console.log ('Swooosh!'); + } + + // good + function fight() { + console.log('Swooosh!'); + } + ``` + +- [19.4](#whitespace--infix-ops) **【必须】** 运算符左右设置各设置一个空格 eslint: [`space-infix-ops`](https://eslint.org/docs/rules/space-infix-ops.html) + + ```javascript + // bad + const x=y+5; + + // good + const x = y + 5; + ``` + +- [19.5](#whitespace--newline-at-end) **【必须】** 在文件的结尾需要保留一个空行 eslint: [`eol-last`](https://github.com/eslint/eslint/blob/master/docs/rules/eol-last.md) + + ```javascript + // bad + import { es6 } from './AirbnbStyleGuide'; + // ... + export default es6; + ``` + + ```javascript + // bad + import { es6 } from './AirbnbStyleGuide'; + // ... + export default es6;↵ + ↵ + ``` + + ```javascript + // good + import { es6 } from './AirbnbStyleGuide'; + // ... + export default es6;↵ + ``` + +- [19.6](#whitespace--chains) **【推荐】** 在编写多个方法链式调用(超过两个方法链式调用)时。 使用前导点,强调这行是一个方法调用,而不是一个语句。 + eslint: [`newline-per-chained-call`](https://eslint.org/docs/rules/newline-per-chained-call) [`no-whitespace-before-property`](https://eslint.org/docs/rules/no-whitespace-before-property) + + ```javascript + // bad + $('#items').find('.selected').highlight().end().find('.open').updateCount(); + + // bad + $('#items'). + find('.selected'). + highlight(). + end(). + find('.open'). + updateCount(); + + // good + $('#items') + .find('.selected') + .highlight() + .end() + .find('.open') + .updateCount(); + + // bad + const leds = stage.selectAll('.led').data(data).enter().append('svg:svg').classed('led', true) + .attr('width', (radius + margin) * 2).append('svg:g') + .attr('transform', `translate(${radius + margin},${radius + margin})`) + .call(tron.led); + + // good + const leds = stage.selectAll('.led') + .data(data) + .enter().append('svg:svg') + .classed('led', true) + .attr('width', (radius + margin) * 2) + .append('svg:g') + .attr('transform', `translate(${radius + margin},${radius + margin})`) + .call(tron.led); + + // good + const leds = stage.selectAll('.led').data(data); + ``` + +- [19.7](#whitespace--after-blocks) **【推荐】** 在块和下一个语句之前留下一空白行。 + + ```javascript + // bad + if (foo) { + return bar; + } + return baz; + + // good + if (foo) { + return bar; + } + + return baz; + + // bad + const obj = { + foo() { + }, + bar() { + }, + }; + return obj; + + // good + const obj = { + foo() { + }, + + bar() { + }, + }; + + return obj; + + // bad + const arr = [ + function foo() { + }, + function bar() { + }, + ]; + return arr; + + // good + const arr = [ + function foo() { + }, + + function bar() { + }, + ]; + + return arr; + ``` + +- [19.8](#whitespace--padded-blocks) **【必须】** 不要在块的开头使用空白行。 eslint: [`padded-blocks`](https://eslint.org/docs/rules/padded-blocks.html) + + ```javascript + // bad + function bar() { + + console.log(foo); + + } + + // bad + if (baz) { + + console.log(qux); + } else { + console.log(foo); + + } + + // bad + class Foo { + + constructor(bar) { + this.bar = bar; + } + } + + // good + function bar() { + console.log(foo); + } + + // good + if (baz) { + console.log(qux); + } else { + console.log(foo); + } + ``` + +- [19.9](#whitespace--no-multiple-blanks) **【必须】** 不要使用多个空行填充代码。 eslint: [`no-multiple-empty-lines`](https://eslint.org/docs/rules/no-multiple-empty-lines) + + + ```javascript + // bad + class Person { + constructor(fullName, email, birthday) { + this.fullName = fullName; + + + this.email = email; + + + this.setAge(birthday); + } + + + setAge(birthday) { + const today = new Date(); + + + const age = this.getAge(today, birthday); + + + this.age = age; + } + + + getAge(today, birthday) { + // .. + } + } + + // good + class Person { + constructor(fullName, email, birthday) { + this.fullName = fullName; + this.email = email; + this.setAge(birthday); + } + + setAge(birthday) { + const today = new Date(); + const age = getAge(today, birthday); + this.age = age; + } + + getAge(today, birthday) { + // .. + } + } + ``` + +- [19.10](#whitespace--in-parens) **【必须】** 不要在括号内添加空格。 eslint: [`space-in-parens`](https://eslint.org/docs/rules/space-in-parens.html) + + ```javascript + // bad + function bar( foo ) { + return foo; + } + + // good + function bar(foo) { + return foo; + } + + // bad + if ( foo ) { + console.log(foo); + } + + // good + if (foo) { + console.log(foo); + } + ``` + +- [19.11](#whitespace--in-brackets) **【必须】** 不要在中括号中添加空格。 eslint: [`array-bracket-spacing`](https://eslint.org/docs/rules/array-bracket-spacing.html) + + ```javascript + // bad + const foo = [ 1, 2, 3 ]; + console.log(foo[ 0 ]); + + // good + const foo = [1, 2, 3]; + console.log(foo[0]); + ``` + +- [19.12](#whitespace--in-braces) **【推荐】** 在花括号内添加空格。 eslint: [`object-curly-spacing`](https://eslint.org/docs/rules/object-curly-spacing.html) + + ```javascript + // bad + const foo = {clark: 'kent'}; + + // good + const foo = { clark: 'kent' }; + ``` + +- [19.13](#whitespace--max-len) **【可选】** 避免让你的代码行超过120个字符(包括空格)。 注意:根据上边的[规则](#strings--line-length) ,长字符串编写可不受该规则约束,不应该被分解。 eslint: [`max-len`](https://eslint.org/docs/rules/max-len.html) + + > 原因? 这样能够提升代码可读性和可维护性。 + + ```javascript + // bad + const foo = jsonData && jsonData.foo && jsonData.foo.bar && jsonData.foo.bar.baz && jsonData.foo.bar.baz.quux && jsonData.foo.bar.baz.quux.xyzzy; + + // bad + $.ajax({ method: 'POST', url: 'https://airbnb.com/', data: { name: 'John' } }).done(() => console.log('Congratulations!')).fail(() => console.log('You have failed this city.')); + + // good + const foo = jsonData + && jsonData.foo + && jsonData.foo.bar + && jsonData.foo.bar.baz + && jsonData.foo.bar.baz.quux + && jsonData.foo.bar.baz.quux.xyzzy; + + // better + const foo = jsonData + ?.foo + ?.bar + ?.baz + ?.quux + ?.xyzzy; + + // good + $.ajax({ + method: 'POST', + url: 'https://airbnb.com/', + data: { name: 'John' }, + }) + .done(() => console.log('Congratulations!')) + .fail(() => console.log('You have failed this city.')); + ``` + +- [19.14](#whitespace--block-spacing) **【必须】** 要求打开的块标志和同一行上的标志拥有一致的间距。此规则还会在同一行关闭的块标记和前边的标记强制实施一致的间距。 eslint: [`block-spacing`](https://eslint.org/docs/rules/block-spacing) + + ```javascript + // bad + function foo() {return true;} + if (foo) { bar = 0;} + + // good + function foo() { return true; } + if (foo) { bar = 0; } + ``` + +- [19.15](#whitespace--comma-spacing) **【必须】** 逗号之前避免使用空格,逗号之后需要使用空格。eslint: [`comma-spacing`](https://eslint.org/docs/rules/comma-spacing) + + ```javascript + // bad + const arr = [1 , 2]; + + // good + const arr = [1, 2]; + ``` + +- [19.16](#whitespace--computed-property-spacing) **【推荐】** 不要在计算属性括号内插入空格。eslint: [`computed-property-spacing`](https://eslint.org/docs/rules/computed-property-spacing) + + ```javascript + // bad + obj[foo ] + obj[ 'foo'] + var x = {[ b ]: a} + obj[foo[ bar ]] + + // good + obj[foo] + obj['foo'] + var x = { [b]: a } + obj[foo[bar]] + ``` + +- [19.17](#whitespace--func-call-spacing) **【必须】** 避免在函数名及其入参括号之间插入空格。 eslint: [`func-call-spacing`](https://eslint.org/docs/rules/func-call-spacing) + + ```javascript + // bad + func (); + + func + (); + + // good + func(); + ``` + +- [19.18](#whitespace--key-spacing) **【必须】** 在对象的属性和值之间的冒号前不加空格,冒号后加空格。 eslint: [`key-spacing`](https://eslint.org/docs/rules/key-spacing) + + ```javascript + // bad + var obj = { foo : 42 }; + var obj2 = { foo:42 }; + + // good + var obj = { foo: 42 }; + ``` + +- [19.19](#whitespace--no-trailing-spaces) **【必须】** 避免在行尾添加空格。 eslint: [`no-trailing-spaces`](https://eslint.org/docs/rules/no-trailing-spaces) + +- [19.20](#whitespace--no-multiple-empty-lines) **【必须】** 在代码开始处不允许存在空行,行间避免出现多个空行,而结尾处必须保留一个空行。 eslint: [`no-multiple-empty-lines`](https://eslint.org/docs/rules/no-multiple-empty-lines) + + ```javascript + // bad + const x = 1; + + + + const y = 2; + + // good + const x = 1; + + const y = 2; + ``` + +- [19.21](#linebreak-style) **【推荐】** 推荐使用 Unix 的 LF 作为换行符,而不是 Windows 的 CRLF,这样可以统一文件的换行符,避免因为换行符导致的格式混乱。 + +## 20. 逗号 + +- [20.1](#commas--leading-trailing) **【必须】** 逗号**不能**前置 eslint: [`comma-style`](https://eslint.org/docs/rules/comma-style.html) + + ```javascript + // bad + const story = [ + once + , upon + , aTime + ]; + + // good + const story = [ + once, + upon, + aTime, + ]; + + // bad + const hero = { + firstName: 'Ada' + , lastName: 'Lovelace' + , birthYear: 1815 + , superPower: 'computers' + }; + + // good + const hero = { + firstName: 'Ada', + lastName: 'Lovelace', + birthYear: 1815, + superPower: 'computers', + }; + ``` + +- [20.2](#commas--dangling) **【推荐】** 添加尾随逗号: **可以** eslint: [`comma-dangle`](https://eslint.org/docs/rules/comma-dangle.html) + + > 原因? 在 git diff 时能够更加清晰地查看改动。 另外,像[Babel](https://babeljs.io/)这样的编译器,会在转译时删除代码中的尾逗号,这意味着你不必担心旧版浏览器中的[尾随逗号问题](https://github.com/airbnb/javascript/blob/es5-deprecated/es5/README.md#commas) 。 + + ```diff + // bad - 没有尾随逗号的 git 差异 + const hero = { + firstName: 'Florence', + - lastName: 'Nightingale' + + lastName: 'Nightingale', + + inventorOf: ['coxcomb chart', 'modern nursing'] + }; + + // good - 有尾随逗号的 git 差异 + const hero = { + firstName: 'Florence', + lastName: 'Nightingale', + + inventorOf: ['coxcomb chart', 'modern nursing'], + }; + ``` + + ```javascript + // bad + const hero = { + firstName: 'Dana', + lastName: 'Scully' + }; + + const heroes = [ + 'Batman', + 'Superman' + ]; + + // good + const hero = { + firstName: 'Dana', + lastName: 'Scully', + }; + + const heroes = [ + 'Batman', + 'Superman', + ]; + + // bad + function createHero( + firstName, + lastName, + inventorOf + ) { + // does nothing + } + + // good + function createHero( + firstName, + lastName, + inventorOf, + ) { + // does nothing + } + + // good (注意逗号不能出现在 "rest" 元素后边) + function createHero( + firstName, + lastName, + inventorOf, + ...heroArgs + ) { + // does nothing + } + + // bad + createHero( + firstName, + lastName, + inventorOf + ); + + // good + createHero( + firstName, + lastName, + inventorOf, + ); + + // good (注意逗号不能出现在 "rest" 元素后边) + createHero( + firstName, + lastName, + inventorOf, + ...heroArgs + ); + ``` + +## 21. jQuery + +- [21.1](#jquery--dollar-prefix) **【推荐】** 对于 jQuery 对象一律使用 `$` 符作为前缀。 + + ```javascript + // bad + const sidebar = $('.sidebar'); + + // good + const $sidebar = $('.sidebar'); + + // good + const $sidebarBtn = $('.sidebar-btn'); + ``` + +- [21.2](#jquery--cache) **【推荐】** 缓存 jQuery 查询,节省 DOM 查询开销。 + + ```javascript + // bad + function setSidebar() { + $('.sidebar').hide(); + + // ... + + $('.sidebar').css({ + 'background-color': 'pink', + }); + } + + // good + function setSidebar() { + const $sidebar = $('.sidebar'); + $sidebar.hide(); + + // ... + + $sidebar.css({ + 'background-color': 'pink', + }); + } + ``` + +- [21.3](#jquery--find) **【推荐】** 能通过一次调用查找到的,不要分多次;在已有对象内查询,使用 `find` 函数,减少重复查询。 + + ```javascript + // bad + $('ul', '.sidebar').hide(); + + // bad + $('.sidebar').find('ul').hide(); + + // good + $('.sidebar ul').hide(); + + // good + $('.sidebar > ul').hide(); + + // good + $sidebar.find('ul').hide(); + ``` + +## 22. 类型转换和强制类型转换 + +- [22.1](#coercion--strings) **【推荐】** 使用 `String()` 函数将变量转成字符串,比较保险: eslint: [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers) + + ```javascript + // => this.reviewScore = 9; + + // bad + const totalScore = new String(this.reviewScore); // typeof totalScore is "object" not "string" + + // bad + const totalScore = this.reviewScore + ''; // invokes this.reviewScore.valueOf() + + // bad + const totalScore = this.reviewScore.toString(); // isn’t guaranteed to return a string + + // good + const totalScore = String(this.reviewScore); + ``` + +- [22.2](#coercion--numbers) **【推荐】** 数字类型转换推荐用 `Number()` 或者 `parseInt()` 函数,其中 `parseInt()` 需显式标明底数。 eslint: [`radix`](https://eslint.org/docs/rules/radix) [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers) + + ```javascript + const inputValue = '4'; + + // bad + const val = new Number(inputValue); + + // bad + const val = +inputValue; + + // bad + const val = inputValue >> 0; + + // bad + const val = parseInt(inputValue); + + // good + const val = Number(inputValue); + + // good + const val = parseInt(inputValue, 10); + ``` + +- [22.3](#coercion--comment-deviations) **【可选】** 如果你对性能有极高的要求,觉得 [`parseInt` 性能太低](https://jsperf.com/coercion-vs-casting/3) ,可以使用位运算,但请用注释说明代码含义,否则很难看懂。 + + ```javascript + // good + /* + * parseInt 使我的代码变慢。 + * 位运算将一个字符串转换成数字更快。 + */ + const val = inputValue >> 0; + ``` + +- [22.4](#coercion--bitwise) **注意:** **【可选】** 谨慎使用位运算符。 在js里,[数字的最大值是64位](https://es5.github.io/#x4.3.19) ,但位运算只能返回32位的整数 ([来源](https://es5.github.io/#x11.7))。 对于大于 32 位的数值,位运算无法得到预期结果。[讨论](https://github.com/airbnb/javascript/issues/109)。 最大的 32 位整数是: 2,147,483,647。 + + ```javascript + 2147483647 >> 0; // => 2147483647 + 2147483648 >> 0; // => -2147483648 + 2147483649 >> 0; // => -2147483647 + ``` + +- [22.5](#coercion--booleans) **【推荐】** 用两个叹号来转换布尔类型: eslint: [`no-new-wrappers`](https://eslint.org/docs/rules/no-new-wrappers) + + ```javascript + const age = 0; + + // bad + const hasAge = new Boolean(age); + + // good + const hasAge = Boolean(age); + + // best + const hasAge = !!age; + ``` + +## 23. 命名规范 + +- [23.1](#naming--descriptive) **【可选】** 避免用单个字母来命名函数或变量。 尽量让名字具有可读性。 + > 补充说明:由于eslint的 [`id-length`](https://eslint.org/docs/rules/id-length) 规则会把for(let i=0; i < len; i++)这种情况也报错,这不太符合我们的习惯,因此在配置中暂时去掉id-length检查。 + + ```javascript + // bad + function q() { + // ... + } + + // good + function query() { + // ... + } + ``` + +- [23.2](#naming--camelCase) **【必须】** 使用驼峰命名法(camelCase)命名对象、函数和实例。 eslint: [`camelcase`](https://eslint.org/docs/rules/camelcase.html) + + ```javascript + // bad + const OBJEcttsssss = {}; + const this_is_my_object = {}; + function c() {} + + // good + const thisIsMyObject = {}; + function thisIsMyFunction() {} + ``` + +- [23.3](#naming--PascalCase) **【必须】** 只有在命名构造器或者类的时候,才用帕斯卡命名法(PascalCase),即首字母大写。 eslint: [`new-cap`](https://eslint.org/docs/rules/new-cap.html) + + ```javascript + // bad + function user(options) { + this.name = options.name; + } + + const bad = new user({ + name: 'nope', + }); + + // good + class User { + constructor(options) { + this.name = options.name; + } + } + + const good = new User({ + name: 'yup', + }); + ``` + +- [23.4](#naming--leading-underscore) **【推荐】** 变量命名时不要使用前置或者后置下划线。 eslint: [`no-underscore-dangle`](https://eslint.org/docs/rules/no-underscore-dangle.html) + + > 因为在 Javascript 里属性和方法没有私有成员一说。 虽然前置下划线通常表示这是私有成员,但实际上还是公开的。 你无法阻止外部调用这类方法。 并且,开发人员容易误以为修改这类函数不需要知会调用方或者不需要测试。 简而言之,如果你想定义私有成员,必须使其不可见。 + + ```javascript + // bad + this.__firstName__ = 'Panda'; + this.firstName_ = 'Panda'; + this._firstName = 'Panda'; + + // good + this.firstName = 'Panda'; + + // 好,在 WeakMap 可用的环境中。 参考 https://kangax.github.io/compat-table/es6/#test-WeakMap + const firstNames = new WeakMap(); + firstNames.set(this, 'Panda'); + ``` + +- [23.5](#naming--self-this) **【推荐】** 不要保存 `this` 的引用,请使用箭头函数或者 [函数#bind](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind)。 + + ```javascript + // bad + function foo() { + const self = this; + return function () { + console.log(self); + }; + } + + // bad + function foo() { + const that = this; + return function () { + console.log(that); + }; + } + + // good + function foo() { + return () => { + console.log(this); + }; + } + ``` + +- [23.6](#naming--filename-matches-export) **【可选】** 文件名应该和默认导出的名称保持一致(文件名建议使用 kebab-case,后缀为小写)。 + + ```javascript + // file 1 contents + class CheckBox { + // ... + } + export default CheckBox; + + // file 2 contents + export default function fortyTwo() { return 42; } + + // file 3 contents + export default function insideDirectory() {} + + // in some other file + // bad + import CheckBox from './checkBox'; // PascalCase import/export, camelCase filename + import FortyTwo from './FortyTwo'; // PascalCase import/filename, camelCase export + import InsideDirectory from './InsideDirectory'; // PascalCase import/filename, camelCase export + + // bad + import CheckBox from './check_box'; // PascalCase import/export, snake_case filename + import forty_two from './forty_two'; // snake_case import/filename, camelCase export + import inside_directory from './inside_directory'; // snake_case import, camelCase export + import index from './inside_directory/index'; // requiring the index file explicitly + import insideDirectory from './insideDirectory/index'; // requiring the index file explicitly + + // good + import CheckBox from './check-box'; // kebab-case export/import/filename + import fortyTwo from './forty-two'; // kebab-case export/import/filename + import insideDirectory from './inside-directory'; // kebab-case export/import/directory name/implicit "index" + // ^ supports both inside-directory.js and inside-directory/index.js + ``` + +- [23.7](#naming--camelCase-default-export) **【必须】** 导出默认函数时使用驼峰命名法,并且文件名应该和方法名相同。文件名建议使用 kebab-case,后缀为小写。 + + ```javascript + function makeStyleGuide() { + // ... + } + + export default makeStyleGuide; + ``` + +- [23.8](#naming--PascalCase-singleton) **【必须】** 当导出构造器 / 类 / 单例 / 函数库 / 对象时应该使用帕斯卡命名法(首字母大写)。 + + ```javascript + const xxxxxxStyleGuide = { + es6: { + }, + }; + + export default xxxxxxStyleGuide; + ``` + +- [23.9](#naming--Acronyms-and-Initialisms) **【推荐】** 缩略词和缩写都必须是全部大写或者全部小写,可读性更好。 + + ```javascript + // bad + import SmsContainer from './containers/sms-container'; + + // bad + const HttpRequests = [ + // ... + ]; + + // good + import SMSContainer from './containers/sms-container'; + + // good + const HTTPRequests = [ + // ... + ]; + + // also good + const httpRequests = [ + // ... + ]; + + // best + import TextMessageContainer from './containers/text-message-container'; + + // best + const requests = [ + // ... + ]; + ``` + +- [23.10](#naming--uppercase) **【可选】** 对于export的常量,可以用全大写命名,但模块内部的常量名不需要全大写(用驼峰试命名可读性更好)。 + + > UPPERCASE_VARIABLES 全大写变量可以让开发者知道这是个常量。 但注意在常量对象内的属性名不需要全大写(如 `EXPORTED_OBJECT.key`)。 + + ```javascript + // bad + const PRIVATE_VARIABLE = 'should not be unnecessarily uppercased within a file'; + + // bad + export const THING_TO_BE_CHANGED = 'should obviously not be uppercased'; + + // bad + export let REASSIGNABLE_VARIABLE = 'do not use let with uppercase variables'; + + // --- + + // 允许,但是不提供语义值 + export const apiKey = 'SOMEKEY'; + + // 多数情况下,很好 + export const API_KEY = 'SOMEKEY'; + + // --- + + // bad - 不必要大写 key 没有增加语义值 + export const MAPPING = { + KEY: 'value' + }; + + // good + export const MAPPING = { + key: 'value' + }; + ``` + +## 24. 存取器 + +- [24.1] **【可选】** 如果没有特殊需要,类属性存取器其实是没有必要的。 + +- [24.2](#accessors--no-getters-setters) **【可选】** 不要使用 JavaScript 的 getters/setters 方法,因为它们会导致意外的副作用,并且更加难以测试、维护和推敲。 相应的,如果你需要处理存取过程的时候可以使用函数 `getVal()` 和 `setVal('hello')` 实现。 + + ```javascript + // bad + class Dragon { + get age() { + // ... + } + + set age(value) { + // ... + } + } + + // good + class Dragon { + getAge() { + // ... + } + + setAge(value) { + // ... + } + } + ``` + +- [24.3](#accessors--boolean-prefix) **【推荐】** 如果属性/方法是一个 `boolean` 值,使用 `isVal()` 或者 `hasVal()`。 + + ```javascript + // bad + if (!dragon.age()) { + return false; + } + + // good + if (!dragon.hasAge()) { + return false; + } + ``` + +- [24.4](#accessors--consistent) **【可选】** 可以创建 `get()` 和 `set()` 方法,但是要保证一致性。 + + ```javascript + class Jedi { + constructor(options = {}) { + const lightsaber = options.lightsaber || 'blue'; + this.set('lightsaber', lightsaber); + } + + set(key, val) { + this[key] = val; + } + + get(key) { + return this[key]; + } + } + ``` + +## 25. 事件 + +- [25.1](#events--hash) **【推荐】** 无论原生 DOM 事件还是像 Backbone 事件这样的自定义事件,在给事件传递参数时,参数应该使用对象而不是单个值。这样未来如果参数有所变化,就不用修改事件回调函数本身。 + + ```javascript + // bad + $(this).trigger('listingUpdated', listing.id); + + // ... + + $(this).on('listingUpdated', (e, listingID) => { + // do something with listingID + }); + ``` + + ```javascript + // good + $(this).trigger('listingUpdated', { listingID: listing.id }); + + // ... + + $(this).on('listingUpdated', (e, data) => { + // do something with data.listingID + }); + ``` + +## 26. 分号 + +- [26.1](#semicolons--required) **【必须】** **要加分号** eslint: [`semi`](https://eslint.org/docs/rules/semi.html) + + > 原因? 当 JavaScript 解析器解析到没有分号的单行代码时,它会使用一个叫做 [自动分号插入算法(Automatic Semicolon Insertion)](https://tc39.github.io/ecma262/#sec-automatic-semicolon-insertion) 来确定是否应该以换行符视为语句的结束,如果判断为语句结束,会在代码中断前插入一个分号到代码中。 但是,ASI 包含了一些奇怪的行为,如果 JavaScript 错误的解释了你的换行符,你的代码将会中断。 随着越来越多的新特性成为 JavaScript 的一部分,这些规则将变得更加复杂。明确地终止你的语句,并配置你的 linter 以捕获缺少分号的代码行,将有助于预防此类问题。 + + ```javascript + // bad - 可能异常 + const jedis = {} + ['luke', 'leia'].some((name) => { + jedis[name] = true + return true + }) + + // bad - 可能异常 + const reaction = "No! That's impossible!" + (async function meanwhileOnTheFalcon() { + // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` + // ... + }()) + + // bad - 返回 `undefined` 而不是下一行的值 - 当 `return` 单独一行的时候 ASI 总是会发生 + function foo() { + return + 'search your feelings, you know it to be foo' + } + + // good + const jedis = {}; + ['luke', 'leia'].some((name) => { + jedis[name] = true; + return true; + }); + + // good + const reaction = "No! That's impossible!"; + (async function meanwhileOnTheFalcon() { + // handle `leia`, `lando`, `chewie`, `r2`, `c3p0` + // ... + }()); + + // good + function foo() { + return 'search your feelings, you know it to be foo'; + } + ``` + +# TypeScript编码规范 + +## 1. 类 + +[1.1](#explicit-member-accessibility) **【可选】** 必须设置类的成员的可访问性。 eslint: [`@typescript-eslint/explicit-member-accessibility`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/explicit-member-accessibility.md) +>原因? +>1、将不需要公开的成员设为私有的,可以增强代码的可理解性,对文档输出也很友好 +>2、将暴露出去的设置为public的,类和外界的联系一目了然 +> + + ```typescript + // bad +class Foo2 { + static foo = 'foo'; + static getFoo() { + return Foo2.foo; + } + constructor() {} + bar = 'bar'; + getBar() {} + get baz() { + return 'baz'; + } + set baz(value) { + console.log(value); + } +} + + // good + class Foo2 { + private static foo = 'foo'; + public static getFoo() { + return Foo2.foo; + } + public constructor() {} + protected bar = 'bar'; + public getBar() {} + public get baz() { + return 'baz'; + } + public set baz(value) { + console.log(value); + } +} + ``` + +[1.2](#member-ordering) **【必须】** 指定类成员的排序规则。 eslint: [`@typescript-eslint/member-ordering`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/member-ordering.md) + +>优先级: + +1. static > instance +2. field > constructor > method +3. public > protected > private + +```typescript +// bad +class Foo1 { + private getBar3() { + return this.bar3; + } + protected getBar2() {} + public getBar1() {} + public constructor() { + console.log(Foo1.getFoo3()); + console.log(this.getBar3()); + } + private bar3 = 'bar3'; + protected bar2 = 'bar2'; + public bar1 = 'bar1'; + private static getFoo3() { + return Foo1.foo3; + } + protected static getFoo2() {} + public static getFoo1() {} + private static foo3 = 'foo3'; + protected static foo2 = 'foo2'; + public static foo1 = 'foo1'; +} + +// good +class Foo2 { + public static foo1 = 'foo1'; + protected static foo2 = 'foo2'; + private static foo3 = 'foo3'; + public static getFoo1() {} + protected static getFoo2() {} + private static getFoo3() { + return Foo2.foo3; + } + public bar1 = 'bar1'; + protected bar2 = 'bar2'; + private bar3 = 'bar3'; + public constructor() { + console.log(Foo2.getFoo3()); + console.log(this.getBar3()); + } + public getBar1() {} + protected getBar2() {} + private getBar3() { + return this.bar3; + } +} + +``` + +[1.3](#no-parameter-properties) **【可选】** 禁止给类的构造函数的参数添加修饰符。 eslint: [`@typescript-eslint/no-parameter-properties`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-parameter-properties.md) + >原因?强制所有属性都定义到类里面,比较统一 + + ```typescript +// bad +class Foo1 { + constructor(private name: string) {} +} + +// good +class Foo2 { + constructor(name: string) {} +} + ``` + +## 2. 函数 + +[2.1](#adjacent-overload-signatures) **【必须】** 重载的函数必须写在一起,增强可读性。 eslint: [`@typescript-eslint/adjacent-overload-signatures`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/adjacent-overload-signatures.md) + + ```typescript + // bad + declare namespace NSFoo1 { + export function foo(s: string): void; + export function foo(n: number): void; + export function bar(): void; + export function foo(sn: string | number): void; +} + +type TypeFoo1 = { + foo(s: string): void; + foo(n: number): void; + bar(): void; + foo(sn: string | number): void; +}; + +interface IFoo1 { + foo(s: string): void; + foo(n: number): void; + bar(): void; + foo(sn: string | number): void; +} + + // good + declare namespace NSFoo2 { + export function foo(s: string): void; + export function foo(n: number): void; + export function foo(sn: string | number): void; + export function bar(): void; +} + +type TypeFoo2 = { + foo(s: string): void; + foo(n: number): void; + foo(sn: string | number): void; + bar(): void; +}; + +interface IFoo2 { + foo(s: string): void; + foo(n: number): void; + foo(sn: string | number): void; + bar(): void; +} + ``` + +[2.2](#unified-signatures) **【必须】** 函数重载时,若能通过联合类型将两个函数的类型声明合为一个,则使用联合类型而不是两个函数声明。 eslint: [`@typescript-eslint/unified-signatures`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/unified-signatures.md) + +```typescript +// bad +function foo1(x: number): boolean; +function foo1(x: string): boolean; +function foo1(x: any): boolean { + return parseInt(x, 10) > 0; +} + +// good +function foo2(x: number | string): boolean { + return parseInt(x, 10) > 0; +} +``` + +## 3. 类型 + + [3.1](#consistent-type-assertions) **【必须】** 类型断言必须使用 as Type,禁止使用 \,禁止对对象字面量进行类型断言(断言成 any 是允许的)。 eslint: [`@typescript-eslint/consistent-type-assertions`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/consistent-type-assertions.md) + >原因?避免Type被理解为 jsx + + ```typescript +// bad +let bar1: string | number; +const foo1 = bar1; + +// good +let bar2: string | number; +const foo2 = bar2 as string; + +// bad +const baz1 = { + bar: 1 +} as object; + +// good +const baz2 = { + bar: 1 +} as any; + ``` + +[3.2](#no-inferrable-types) **【推荐】** 禁止给一个初始化时直接赋值为 number, string 的变量显式的声明类型, 可以简化代码。 eslint: [`@typescript-eslint/no-inferrable-types`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-inferrable-types.md) + +```typescript +// bad +let foo1: number = 1; +let bar1: string = ''; + +// good +const foo2 = 1; +const bar2 = ''; +``` + + [3.3](#typedef) **【必须】** interface 和 type 定义时必须声明成员的类型。 eslint: [`@typescript-eslint/typedef`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/typedef.md) + + ```typescript +// bad +type Foo1 = { + bar; + baz; +}; + +// good +type Foo2 = { + bar: boolean; + baz: string; +}; + ``` + +[3.4](#prefer-function-type) **【推荐】** 使用函数类型别名替代包含函数调用声明的接口。 eslint: [`@typescript-eslint/prefer-function-type`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/prefer-function-type.md) + + ```typescript +// bad +interface Foo1 { + (): string; +} + +// good +type Foo2 = () => string; + ``` + +## 4. 接口 + +[4.1](#consistent-type-definitions) **【可选】** 优先使用 interface 而不是 type。 eslint: [`@typescript-eslint/consistent-type-definitions`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/consistent-type-definitions.md) + >需要被implement, extend 或者merge的建议定义为interface + + ```typescript +type Foo1 = { + foo: string; +}; + +//或者 + +interface Foo2 { + foo: string; +} + + ``` + +[4.2](#method-signature-style) **【可选】** 接口中的方法必须用属性的方式定义。 eslint: [`@typescript-eslint/method-signature-style`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/method-signature-style.md) + >原因?配置了 strictFunctionTypes 之后,用属性的方式定义方法可以获得更严格的检查 + + ```typescript +// bad +interface Foo1 { + bar(): number; +} + +// good +interface Foo1 { + bar: () => number; +} + ``` + +[4.3](#no-empty-interface) **【必须】** 禁止定义空的接口。 eslint: [`@typescript-eslint/no-empty-interface`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-empty-interface.md) + +```typescript +// bad +interface Foo1 {} + +// good +interface Foo2 { + foo: string; +} +``` + +## 5. 命名空间 + +[5.1](#no-namespace) **【必须】** 禁止使用 namespace 来定义命名空间。 eslint: [`@typescript-eslint/no-namespace`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-namespace.md) + >原因?使用 es6 引入模块,才是更标准的方式。 +但是允许使用 declare namespace ... {} 来定义外部命名空间 + +```typescript +// bad +namespace foo1 {} + +// good +declare namespace foo1 {} +``` + +[5.2](#prefer-namespace-keyword) **【必须】** 禁止使用 module 来定义命名空间。 eslint: [`@typescript-eslint/prefer-namespace-keyword`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/prefer-namespace-keyword.md) +>原因?module 已成为 js 的关键字 + + ```typescript +// bad +module Foo1 {} + +// good +namespace Foo2 {} + ``` + +## 6. 语法 + +[6.1](#no-non-null-asserted-optional-chain) **【必须】** 禁止在 optional chaining 之后使用 non-null 断言(感叹号)。 eslint: [`@typescript-eslint/no-non-null-asserted-optional-chain`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-non-null-asserted-optional-chain.md) + >原因?optional chaining 后面的属性一定是非空的 + +```typescript +// bad +let foo1: { bar: string } | undefined; +console.log(foo1?.bar!); + +// good +let foo2: { bar: string } | undefined; +console.log(foo2?.bar); +``` + +[6.2](#no-this-alias) **【必须】** 禁止将 this 赋值给其他变量,除非是解构赋值。 eslint: [`@typescript-eslint/no-this-alias`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-this-alias.md) + + ```typescript + // bad + function foo() { + const self = this; + setTimeout(function () { + self.doWork(); + }); +} + + // good + function foo() { + const { bar } = this; + setTimeout(() => { + this.doWork(); + }); +} + ``` + +[6.3](#no-unused-expressions) **【必须】** 禁止无用的表达式。 eslint: [`@typescript-eslint/no-unused-expressions`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-unused-expressions.md) + + ```typescript +// bad +declare const foo1: any; +declare const bar1: any; +declare const baz1: any; +1; +foo1; +('foo1'); +foo1 && bar1; +foo1 || bar1; +foo1 ? bar1 : baz1; +`bar1`; + +// good +'use strict'; +declare const foo2: any; +declare const bar2: any; +declare const baz2: any; +foo2 && bar2(); +foo2 || bar2(); +foo2 ? bar2() : baz2(); +foo2`bar2`; + + ``` + +[6.4](#prefer-optional-chain) **【必须】** 使用 optional chaining 替代 &&。 eslint: [`@typescript-eslint/prefer-optional-chain`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/prefer-optional-chain.md) +>原因?简化代码 + + ```typescript +// bad + let foo1: any; +console.log(foo1 && foo1.a && foo1.a.b && foo1.a.b.c); + +// good +let foo2: any; +console.log(foo2?.a?.b?.c); + ``` + +## 7. 导入 + +[7.1](#triple-slash-reference) **【必须】** 禁止使用三斜杠导入文件。 eslint: [`@typescript-eslint/triple-slash-reference`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/triple-slash-reference.md) + + ```typescript +// bad +/// + +// good +import Animal from './Animal'; + ``` + +[7.2](#no-require-imports) **【必须】** 禁止使用 require。 eslint: [`@typescript-eslint/no-require-imports`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-require-imports.md) + >原因?统一使用 import 来引入模块,特殊情况使用单行注释允许 require 引入 + + ```typescript + // bad + const fs = require('fs'); + + // good + import * as fs from 'fs'; + ``` + +## 8. 代码风格 + +[8.1](#prefer-for-of) **【推荐】** 使用 for 循环遍历数组时,如果索引仅用于获取成员,则必须使用 for of 循环替代 for 循环。 eslint: [`@typescript-eslint/prefer-for-of`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/prefer-for-of.md) + + ```typescript +// bad +const arr1 = [1, 2, 3]; + +for (let i = 0; i < arr1.length; i++) { + console.log(arr1[i]); +} + +// good +const arr2 = [1, 2, 3]; +for (const x of arr2) { + console.log(x); +} +for (let i = 0; i < arr2.length; i++) { + // i is used to write to arr, so for-of could not be used. + arr2[i] = 0; +} +for (let i = 0; i < arr2.length; i++) { + // i is used independent of arr, so for-of could not be used. + console.log(i, arr2[i]); +} + + ``` + +[8.2](#type-annotation-spacing) **【必须】** 在类型注释周围需要一致的间距。 eslint: [`@typescript-eslint/type-annotation-spacing`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/type-annotation-spacing.md) + + ```typescript +// bad +let foo:string = "bar"; +let foo :string = "bar"; +let foo : string = "bar"; + +function foo():string {} +function foo() :string {} +function foo() : string {} + +class Foo { + name:string; +} + +class Foo { + name :string; +} + +class Foo { + name : string; +} + +type Foo = ()=> {}; + +// good +let foo: string = 'bar'; + +function foo(): string {} + +class Foo { + name: string; +} + +type Foo = () => {}; + ``` + +[更多信息](https://stackoverflow.com/questions/7365172/semicolon-before-self-invoking-function/7365214#7365214) + +## 9. 命名方式 + +[9.1](#naming-convention-class) **【推荐】** 变量和函数使用驼峰法进行命名。 eslint: [`@typescript-eslint/naming-convention`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/naming-convention.md) + +> 对应 JS 规范中的 camelCase 规则 + +```typescript +// bad +const FOO = 123; +const FOO_REF = () => {}; +function FOO_FUNCTION() {}; + +// good +const foo = 123; +const fooRef = () = {}; +function fooFunction() {}; +``` + +[9.2](#naming-convention-exported-varible) **【推荐】** 导出的常规变量使用全大写,下划线分割单词。但是对象、函数、类实例等使用 camelCase。 eslint: [`@typescript-eslint/naming-convention`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/naming-convention.md) + +```typescript +// bad +export const foo = 123; +export const bar = 'abc'; +export const INSTANCE = new Object(); + +// good +export const FOO = 123; +export const BAR = 'abc'; +export const instance = new Object(); +``` + +[9.3](#naming-convention-react-component) **【推荐】** React 组件使用 Pascal 写法。 eslint: [`@typescript-eslint/naming-convention`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/naming-convention.md) + +```typescript +// bad +const bar = ; + +// good +const Bar = ; +``` + +[9.4](#class-type-naming-convention) **【推荐】** 类名和类型定义使用首字母大写。 eslint: [`@typescript-eslint/naming-convention`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/naming-convention.md) + +```typescript +// bad +interface fOo { +} + +class fOo implements fOo { + +} + +// good +interface Foo { +} + +class Foo implements Foo { + +} +``` + +[9.5](#class-property-naming-convention) **【推荐】** 类成员使用驼峰法,并阻止使用下划线开头和结尾。 eslint: [`@typescript-eslint/naming-convention`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/naming-convention.md) + +```typescript +// bad +class Foo { + __str__ = 'foobar'; // 属性上带有下划线 + + public Print() { // 首字母大写 + this.__log__(); // 前后带有下划线 + } + + private __log__() { + console.log(this.__str__); + } +} + +// good +class Foo { + str = 'foobar'; + + public print() { + this.log(); + } + + private log() { + console.log(this.str); + } +} +``` + +## 10. Promise 和 async await + +- [10.1](#promimse--no-misused-promises) **【必须】** 禁止对条件语句中 promise 的误用。 eslint: [`@typescript-eslint/no-misused-promises`](https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-misused-promises.md) + +> 条件语句中的 promise 恒为真,需要用 await 才能获取异步调用后的返回值。 + +```javascript +const promise = (value) => new Promise((resolve, reject) => { + setTimeout(() => resolve(value), 1000); +}); + +async function foo() { + // bad - 恒为真 + if (promise(1)) { + // Do something + } + + // good - 使用 await 获取异步调用后的返回值 + if (await promise(1)) { + // Do something + } +} +``` \ No newline at end of file diff --git a/python/hello_python.md b/python/hello_python.md new file mode 100644 index 0000000..c756ce6 --- /dev/null +++ b/python/hello_python.md @@ -0,0 +1,1826 @@ +# Python 编码风格与规范 + +[TOC] + + +## 前言 + +为了让不同编码习惯的开发者更好的协作配合,并且形成良好的基础编码规范与风格,我们以 [PEP8](https://www.python.org/dev/peps/pep-0008/) 为基础,修改了陈旧的规则,丰富了示例,并整理了工作中常见的不规范操作,最终形成此 Python 编码规范与风格。 + +本规范适用于所有使用 Python 语言作为开发语言的软件产品。 + +由于 Python2 在 [2020 年停止维护](https://www.python.org/doc/sunset-python-2/),建议新增的项目使用 Python3.6+,可以使用到更多的高级特性。如果项目有兼容性需求需要支持老版本 Python 的,那么不涉及的特性可以忽略。 本规范的示例采用符合 Python3.6+ 的语法。 + +- **必须(Mandatory)**:用户必须采用; +- **推荐(Preferable)**:用户理应采用,但如有特殊情况,可以不采用; +- **可选(Optional)**:用户可参考,自行决定是否采用; + +未明确指明的则默认为 **必须(Mandatory)**。 + +License + +查看 [NOTICE](./NOTICE) 文件了解注明和鸣谢信息。 + + +## 一、编码风格 + +规范地代码布局有助于帮助开发者更容易地理解业务逻辑。 + + + + + +### 1.1 缩进 + + +[1.1.1](<#1.1.1>) **【必须】** 对于每级缩进,统一要求使用4个 空格 ,而非 tab 键。 pylint:`bad-indentation`. + + + + +[1.1.2](<#1.1.2>) **【必须】** 续行,要求使用括号等定限界符,并且需要垂直对齐。 + + + + +***正确示范*** + +```python +# 与定界(括号)符对齐 +foo = long_function_name(var_one, var_two, + var_three, var_four) + +# 换行并增加4个额外的空格(一级缩进) +def long_function_name( + var_one, var_two, var_three, + var_four): + print(var_one) + +# 悬挂需要增加一级缩进 +foo = long_function_name( + var_one, var_two, + var_three, var_four) +``` + + +***错误示范*** + +```python + +# 当不使用垂直对齐时,第一行不允许加参数 +foo = long_function_name(var_one, var_two, + var_three, var_four) + +# 下面这种情况,需要增加额外的缩进,否则无法区分代码所在的缩进级别 +def long_function_name( + var_one, var_two, var_three, + var_four): + print(var_one) + +``` + + +[1.1.3](<#1.1.3>) **【推荐】** 如果包含定界符(括号,中括号,大括号)的表达式跨越多行,那么定界符的扩回符, 可以放置与最后一行的非空字符对齐或者与构造多行的开始第一个字符对齐。 + + + + +***正确示范*** + +```python +# 与最后一行的非空字符对齐 +my_list = [ + 1, 2, 3, + 4, 5, 6, + ] +result = some_function_that_takes_arguments( + 'a', 'b', 'c', + 'd', 'e', 'f', + ) + +# 或者与开始构造多行的第一个字符对齐 +my_list = [ + 1, 2, 3, + 4, 5, 6, +] +result = some_function_that_takes_arguments( + 'a', 'b', 'c', + 'd', 'e', 'f', +) +``` + + +[1.1.4](<#1.1.4>) **【推荐】** 对于会经常改动的函数参数、列表、字典定义,建议每行一个元素,并且每行增加一个`,` 。 + + + + +***正确示范*** + +```python +yes = ('y', 'Y', 'yes', 'TRUE', 'True', 'true', 'On', 'on', '1') # 基本不再改变 + +kwlist = [ + 'False', + 'None', + 'True', + 'and', + 'as', + 'assert', + ... + 'yield', # 最后一个元素也增加一个逗号 ,方便以后diff不显示此行 +] + +person = { + 'name': 'bob', + 'age': 12, # 可能经常增加字段 +} +``` + + +***错误示范*** + +```python +# 关键字会不断增加,每个元素都换行 +kwlist = ['False', 'None', 'True', 'and', 'as', + 'assert', 'async', ... +] + +person = {'name': 'bob', 'age': 12} +``` + + +[1.1.5](<#1.1.5>) **【可选】** 对于 if 判断,一般来说尽量不要放置过多的判断条件。换行时增加 4 个额外的空格。 pycodestyle:`E129 visually indented line with same indent as next logical line`. + +> 备注:PEP8没有明确规定,以下几种都是允许的。建议使用前面2种方法,后2种会与已有的开源工具冲突。 + + + +***正确示范*** + +```python +# 更推荐:在续行中,增加额外的缩进级别。允许 and 操作符在前 +if (this_is_one_thing + and that_is_another_thing): + do_something() + +# 更推荐:在续行中,增加额外的缩进级别 +if (this_is_one_thing and + that_is_another_thing): + do_something() + +# 允许:与定界符(括号)对齐,不需要额外的缩进 +if (this_is_one_thing and + that_is_another_thing): + do_something() + +# 允许:增加注释,编辑器会提示语法高亮,有助于区分 +if (this_is_one_thing and + that_is_another_thing): + # Since both conditions are true, we can frobnicate. + do_something() +``` + + + + + + +### 1.2 每行最大长度 + + +[1.2.1](<#1.2.1>) **【必须】** 每行最多不超过`120`个字符。每行代码最大长度限制的根本原因是过长的行会导致阅读障碍,使得缩进失效。 pylint:`line-too-long`. + +除了以下两种情况例外: +1. 导入模块语句。 +2. 注释中包含的URL。 + +如果需要一个长的字符串,可以用括号实现隐形连接。 + + + +***正确示范*** + +```python +x = ('This will build a very long long ' + 'long long long long long long string') +``` + + + + + + +### 1.3 空白符 + + +[1.3.1](<#1.3.1>) **【必须】** 在表达式的赋值符号、操作符左右至少有一个空格。 + + + + +***正确示范*** + +```python +x = y + 1 +``` + + +***错误示范*** + +```python +x=y+1 +x = y+1 +``` + + +[1.3.2](<#1.3.2>) **【必须】** 禁止行尾空白。 pylint:`trailing-whitespace`. + +行尾空白虽然不会造成功能性异常,但是这些空白字符会被源码管理系统标记出来显示为差异,对开发人员造成困恼。 + + + +***正确示范*** + +```diff +# YES: 尾部没有空白符号 ++ para = {} ++ para = {} # comment +``` + + +***错误示范*** + +```diff +# No: 结尾存在多余空白符号 +- para = {}••••• +- para = {} # comment•••••• +``` + + + + + + +### 1.4 操作符 + + +[1.4.1](<#1.4.1>) **【推荐】** Python 没有三目操作符,对于二目操作符来说,操作符允许在换行符之后出现。 + +> 备注:pycodestyle 工具与此条目相反,PEP8 推荐操作符在这之前,更具备可读性。[PEP8: Should a Line Break Before or After a Binary Operator?](https://www.python.org/dev/peps/pep-0008/#should-a-line-break-before-or-after-a-binary-operator)。 屏蔽 pycodestyle:`W503 line break before binary operator` + + + +***正确示范*** + +```python +# YES: 易于将运算符与操作数匹配,可读性高 +income = (gross_wages + + taxable_interest + + (dividends - qualified_dividends) + - ira_deduction + - student_loan_interest) +``` + + +***错误示范*** + +```python +# No: 运算符的位置远离其操作数 +income = (gross_wages + + taxable_interest + + (dividends - qualified_dividends) - + ira_deduction - + student_loan_interest) +``` + + + + + + +### 1.5 括号 + + +[1.5.1](<#1.5.1>) **【必须】** tuple 元组不允许逗号结尾,显式增加括号规避。即使一个元素也加上括号。 pylint:`trailing-comma-tuple`. + +行尾的逗号可能导致本来要定义一个简单变量,结果变成 tuple 变量。 + + +***正确示范*** + +```python +trailingcomma = (['f'],) + +return (1,) +``` + + +***错误示范*** + +```python +trailingcomma = ['f'], # tuple + +return 1, +``` + + + + + + +### 1.6 空行 + + +[1.6.1](<#1.6.1>) **【必须】** 模块中的一级函数和类定义之间,需要`空两行`。 pycodestyle:`E302 expected 2 blank lines`. + + + + +[1.6.2](<#1.6.2>) **【必须】** 类中函数定义之间,`空一行`。 pycodestyle:`E302 expected 1 blank line`. + + + + +[1.6.3](<#1.6.3>) **【必须】** 源文件须使用且仅使用 `一个换行符` 作为结尾。 pylint:`missing-final-newline`, `trailing-newlines`. + + + + +[1.6.4](<#1.6.4>) **【必须】** 通常每个语句应该独占一行。 pylint:`multiple-statements`. + +如果测试结果与测试语句在一行放得下,你也可以将它们放在同一行。 如果是`if`语句, 只有在没有`else`时才能这样做。 特别地,绝不要对 `try`/`except` 这样做,因为`try`和`except`不能放在同一行。 + + +***正确示范*** + +```python +if foo: + bar(foo) +else: + baz(foo) + +try: + bar(foo) +except ValueError: + baz(foo) +``` + + +***错误示范*** + +``` python +if foo: bar(foo) +else: baz(foo) + +try: bar(foo) +except ValueError: baz(foo) + +try: + bar(foo) +except ValueError: baz(foo) +``` + + +[1.6.5](<#1.6.5>) **【推荐】** 可以在代码段中的`空一行`来区分不同业务逻辑块。 + + + +```python +"""This is the example module. + +This module does stuff. +""" + + +import os + + +def foo(): + pass + + +class MyClass(): + + def __init__(self): + pass + + def foo(self): + pass + + +class AnotherClass(object): + """Another class. + + This is some comments for another class + """ + + def __init__(self, + a, + b): + if a > b: + self._min = b + self._max = a + + else: + self._min = a + self._max = b + + self._gap = self._max = self._min + + def foo(self): + pass + +``` + + + + + +### 1.7 源文件编码 + + +[1.7.1](<#1.7.1>) **【必须】** 源文件编码需统一使用 `UTF-8` 编码,以下内容需要增加到每一个python文件的头部。 + +```python +# -*- coding: utf-8 -*- +``` + + + +[1.7.2](<#1.7.2>) **【必须】** **避免不同操作系统对文件换行处理的方式不同,一律使用`LF`**。 pylint:`mixed-line-endings`, `unexpected-line-ending-format`. + + + + + + + + +### 1.8 Shebang + + +[1.8.1](<#1.8.1>) **【必须】** 程序的main文件应该以 `#!/usr/bin/env python2` 或者 `#!/usr/bin/env python3` 开始, 可以同时支持Python2、Python3的`#!/usr/bin/env python`。 + +非程序入口的文件不应该出现 Shebang 。 + + +***正确示范*** + +```python +#!/usr/bin/env python3 +# -*- coding: utf-8 -*- +# +``` + + + + + + +### 1.9 模块引用(import) + + +[1.9.1](<#1.9.1>) **【必须】** 每个导入应该独占一行。 pylint:`multiple-imports`. + + + + +***正确示范*** + +```python +import os +import sys +``` + + +***错误示范*** + +```python +import os, sys +``` + + +[1.9.2](<#1.9.2>) **【必须】** 导入总应该放在文件顶部,位于模块注释和文档字符串之后,模块全局变量和常量之前。 pylint:`wrong-import-order`. + +导入应该按照从最通用到最不通用的顺序分组, 每个分组之间,需要空一行: + +* 标准库导入 +* 第三方库导入 +* 本地导入 + +每种分组中,建议每个模块的完整包路径按 ***字典序*** 排序,并忽略大小写。 + + + +***正确示范*** + +```python +import foo +from foo import bar +from foo.bar import baz +from foo.bar import Quux +from Foob import ar +``` + + +[1.9.3](<#1.9.3>) **【必须】** 避免使用 `from import *`,因为可能会造成命名空间的污染。 pylint:`wildcard-import`. + + + + +[1.9.4](<#1.9.4>) **【必须】** 禁止导入了模块却不使用它。 pylint:`unused-import`. + + + + +***正确示范*** + +```python +import os # used + +dir_path = os.path.abspath('.') +``` + + +***错误示范*** + +```python +import os # unused ! + +# dir_path = os.path.abspath('.') +``` + + + + + + +### 1.10 模块中的魔术变量(dunders) + + +[1.10.1](<#1.10.1>) **【必须】** 对于两个 `_` 开头和两个 `_` 结尾的变量, 如 `__all__`,`__author__`,`__version__`等,应该放在模块文档之后, 其他模块导入之前(`__future__` 除外)。 + + + + +[1.10.2](<#1.10.2>) **【必须】** Python 要求 `future` 导入必须出现在其他模块导入之前。 pylint:`misplaced-future`. + + + + +***正确示范*** + +```python +# -*- coding: utf-8 -*- +# +# Copyright @ 2020 + +"""This is the example module. + +This module does stuff. +""" + +from __future__ import barry_as_FLUFL + +__all__ = ['a', 'b', 'c'] +__version__ = '0.1' +__author__ = 'Cardinal Biggles' + +import os +import sys +``` + + + + + + +### 1.11 注释 + +> 有效的注释有助于帮助开发者更快地理解代码,模块,函数,方法,以及行内注释的都有各自的风格。 + +[1.11.1](<#1.11.1>) **【必须】** 所有`#`开头的注释,必须与所在的代码块同级,并置放在代码之上。 pycodestyle:`E262 inline comment should start with '# '`. + + + + +[1.11.2](<#1.11.2>) **【必须】** 注释的每一行都应该以`#`和一个空格开头。 pycodestyle:`E266 too many leading '#' for block comment`, `E262 inline comment should start with '# '`. + + + + +[1.11.3](<#1.11.3>) **【必须】** 行内注释`#`与代码离开至少2个空格。 pycodestyle:`E261 at least two spaces before inline comment`. + + + + +[1.11.4](<#1.11.4>) **【必须】** 块注释:对于复杂的操作,可以在代码之前写若干行注释,对简单的代码,可以放在行内。与代码离开至少2个空格。 + + + + +***正确示范*** + +```python +# this is a very complex operation, please +# read this carefully + +if i & (i-1) == 0: + # do my job ... + +# 单行注释,为可读性,至少离开代码2个空格 +x = x + 1 # Compensate for border +``` + + +[1.11.5](<#1.11.5>) **【必须】** TODO 注释需要加上名字。 + +TODO注释应该在所有开头处包含`TODO`字符串,紧跟着是用括号括起来的你的名字, email地址或其它标识符,然后是一个可选的冒号。 接着必须有一行注释,解释要做什么。 主要目的是为了有一个统一的TODO格式,这样添加注释的人就可以搜索到(并可以按需提供更多细节)。 写了TODO注释并不保证写的人会亲自解决问题。 当你写了一个TODO,请注上你的名字。 + +> 为临时代码使用TODO注释, 它是一种短期解决方案。常见的IDE在提交代码时, 会检查变更中包含了TODO并提醒开发者,防止提交是忘记还有未完成的代码。 +如果TODO是`将来做某事`的形式, 那么请确保包含一个指定的日期或者一个特定的事件(条件)。 +相同地,也可以留下`FIXME`, `NOTES` 注释。 + + + +***正确示范*** + +```python +# TODO(zhangsan): Change this to use relations. +# FIXME(zhangsan@xx.com): Please fix me here. +# NOTES(zhangsan): This is some notes. +``` + + + + + + +### 1.12 文档字符串 + +Docstring 文档字符串提供了将文档与 Python 模块,函数,类和方法相关联的便捷方法。 + +```python +def foobar(): + """Return a foobang + + Optional plotz says to frobnicate the bizbaz first. + """ +``` + +[PEP 257](https://www.python.org/dev/peps/pep-0257/) 全面描述了文档字符串的风格。 + +[1.12.1](<#1.12.1>) **【推荐】** 需对外发布的public 模块,函数,类,方法等需要包含文档字符串。内部使用的方法,函数等,要求使用简单的注释描述功能。 pylint:`missing-module-docstring`, `missing-class-docstring`, `missing-function-docstring`. + +一个函数或方法,如果可以直接被其他开发者使用,需要提供文档明确其含义,需要指出输入,输出,以及异常内容。 + + + +[1.12.2](<#1.12.2>) **【必须】** 第一行应为文档名,空一行后,输入文档描述。 + + + + +[1.12.3](<#1.12.3>) **【推荐】** 在使用文档字符串时,推荐使用 `reStructuredText` 风格类型。 + + + + +***正确示范*** + +```python +def fetch_bigtable_rows(big_table, keys, other_silly_variable=None): + """Fetches rows from a Bigtable. + + Retrieves rows pertaining to the given keys from the Table instance + represented by big_table. Silly things may happen if + other_silly_variable is not None. + + :param big_table: An open Bigtable Table instance. + :param keys: A sequence of strings representing the key of each table row + to fetch. + :param other_silly_variable: Another optional variable, that has a much + longer name than the other args, and which does nothing. + + :return: A dict mapping keys to the corresponding table row data + fetched. Each row is represented as a tuple of strings. For + example: + + {'Serak': ('Rigel VII', 'Preparer'), + 'Zim': ('Irk', 'Invader'), + 'Lrrr': ('Omicron Persei 8', 'Emperor')} + + If a key from the keys argument is missing from the dictionary, + then that row was not found in the table. + + :raises ValueError: if `keys` is empty. + :raises IOError: An error occurred accessing the bigtable.Table object. + """ + pass +``` + + +[1.12.4](<#1.12.4>) **【推荐】** 类应该在其定义下有一个用于描述该类的文档字符串。 如果类有公共属性(Attributes),那么文档中应该有一个属性(Attributes)段, 并且应该遵守和函数参数相同的格式。 + + + + +***正确示范*** + +```python +class SampleClass(object): + """Summary of class here. + + Longer class information.... + Longer class information.... + + :ivar likes_spam: A boolean indicating if we like SPAM or not. + :ivar eggs: An integer count of the eggs we have laid. + """ + + def __init__(self, likes_spam=False): + """Inits SampleClass with blah.""" + self.likes_spam = likes_spam + self.eggs = 0 + + def public_method(self): + """Performs operation blah.""" +``` + + + + + + +### 1.13 类型提示 + + +Python 是动态语言,在运行时无需指定变量类型。 +虽然运行时不会执行函数与变量类型注解,但类型提示有助于阅读代码、重构、静态代码检查与IDE的语法提示。 +推荐在项目中使用该特性。 +更多使用可以参考 [类型标注支持]( https://docs.python.org/zh-cn/3/library/typing.html)。 + +类型提示示例代码 +```python +from typing import List + + +class Container(object): + def __init__(self) -> None: + self.elements: List[int] = [] + + def append(self, element: int) -> None: + self.elements.append(element) + + +def greeting(name: str) -> str: + return 'Hello ' + name + + +# 变量定义 +lang: str = 'zh' +success_code: int = 0 +``` + +[1.13.1](<#1.13.1>) **【必须】** 模块级变量,类和实例变量以及局部变量的注释应在冒号后面有一个空格。 pycodestyle:`E231 missing whitespace after ':'`. + + + + +[1.13.2](<#1.13.2>) **【必须】** 冒号前不应有空格。 + + + + +[1.13.3](<#1.13.3>) **【必须】** 如果有赋值符,则等号在两边应恰好有一个空格。 pycodestyle:`E225 missing whitespace around operator`. + + + + +***正确示范*** + +```python +code: int = 10 + +class Point(object): + coords: Tuple[int, int] = (0, 0) + label: str = '' + +def broadcast(servers: Sequence[Server], + message: str = 'spaces around equality sign') -> None: + pass +``` + + +***错误示范*** + +```python +code:int # No space after colon +code : int # Space before colon + +class Test(object): + result: int=0 # No spaces around equality sign +``` + + +[1.13.4](<#1.13.4>) **【推荐】** 当使用类型提示出现循环引用时,可以在导入的头部使用 `if typing.TYPE_CHECKING` , 且对类型注解使用`双引号`或`单引号`进行修饰。 + + + + +***正确示范*** + +```python +import typing + +if typing.TYPE_CHECKING: # 运行时不导入 + # For type annotation + from typing import Any, Dict, List, Sequence # NOQA + from sphinx.application import Sphinx # NOQA + + +class Parser(docutils.parsers.Parser): + + def set_application(self, app: "Sphinx") -> None: # 同时采用引号 + pass +``` + + + + + + +### 1.14 字符串 + + +[1.14.1](<#1.14.1>) **【推荐】** 即使参数都是字符串, 也要使用%操作符或者格式化方法格式化字符串。不过也不能一概而论, 你需要在+和%之间权衡。 + + + + +***正确示范*** + +```python +# 更推荐 +x = f'name: {name}; score: {n}' # Python3.6+ 以上支持 +x = 'name: {name}; score: {n}'.format(name=name, n=n) +x = 'name: {name}; score: {n}'.format(**{"name": name, "n": n}) +x = 'name: %(name)s; score: %(n)d' % {"name": name, "n": n} + +# 可接受 +x = '%s, %s!' % (imperative, expletive) +x = '{}, {}!'.format(imperative, expletive) +x = 'name: %s; score: %d' % (name, n) +x = 'name: {}; score: {}'.format(name, n) +``` + + +***错误示范*** + +```python +x = '%s%s' % (a, b) # use + in this case +x = '{}{}'.format(a, b) # use + in this case +x = imperative + ', ' + expletive + '!' +x = 'name: ' + name + '; score: ' + str(n) +``` + + +[1.14.2](<#1.14.2>) **【推荐】** 避免在循环中用`+`和`+=`操作符来累加字符串。 由于字符串是不可变的, 这样做会创建不必要的临时对象, 并且导致二次方而不是线性的运行时间。 作为替代方案, 你可以将每个子串加入列表, 然后在循环结束后用 `.join` 连接列表。 (也可以将每个子串写入一个 io.StringIO 缓存中。) pylint:`consider-using-join`. + + + + +***正确示范*** + +```python +items = [''] +for last_name, first_name in employee_list: + items.append('' % (last_name, first_name)) +items.append('
%s, %s
') +employee_table = ''.join(items) +``` + + +***错误示范*** + +```python +employee_table = '' +for last_name, first_name in employee_list: + employee_table += '' % (last_name, first_name) +employee_table += '
%s, %s
' +``` + + +[1.14.3](<#1.14.3>) **【推荐】** 在同一个文件中, 保持使用字符串引号的一致性。 使用单引号`'`或者双引号`"`引用字符串, 并在同一文件中一直沿用这种风格。 当字符串中包含单引号或者双引号时,为提高可读性,使用另外一种引号,代替转义字符。 + + + + +***正确示范*** + +```python +Python('Why are you hiding your eyes?') +Gollum("I'm scared of lint errors.") +Narrator('"Good!" thought a happy Python reviewer.') +``` + + +***错误示范*** + +```python +Python("Why are you hiding your eyes?") +Gollum('The lint. It burns. It burns us.') +Gollum("Always the great lint. Watching. Watching.") +``` + + +[1.14.4](<#1.14.4>) **【必须】** 如果要引用的字符串为多行时,需要使用双引号引用字符串。 + + + + +[1.14.5](<#1.14.5>) **【必须】** 文档字符串(docstring)必须使用三重双引号 `"""`。 + + + + +[1.14.6](<#1.14.6>) **【可选】** 避免在代码中使用三重引号`"""`,因为当使用三重引号时,缩进方式与其他部分不一致,容易引起误导。 + + + + +***正确示范*** + +```python +print("This is much nicer.\n" + "Do it this way.\n") +``` + + +***错误示范*** + +```python +print("""This is pretty ugly. +Don't do this. +""") +``` + + +[1.14.7](<#1.14.7>) **【推荐】** 检查前缀和后缀时,使用 `.startswith()` 和 `.endswith()` 代替字符串切片。 + + + + +***正确示范*** + +```python +if foo.startswith('bar'): +``` + + +***错误示范*** + +```python +if foo[:3] == 'bar': +``` + + + + + + +### 1.15 文件和sockets + + +[1.15.1](<#1.15.1>) **【必须】** 在文件和sockets结束时,显式的关闭它。 + +除文件外, sockets或其他类似文件的对象在没有必要的情况下打开,会有许多副作用,例如: + +1. 它们可能会消耗有限的系统资源,如文件描述符。 如果这些资源在使用后没有及时归还系统,那么用于处理这些对象的代码会将资源消耗殆尽。 +2. 持有文件将会阻止对于文件的其他诸如移动、删除之类的操作。 +3. 仅仅是从逻辑上关闭文件和sockets,那么它们仍然可能会被其共享的程序在无意中进行读或者写操作。只有当它们真正被关闭后,对于它们尝试进行读或者写操作将会抛出异常, 并使得问题快速显现出来。 + +而且,幻想当文件对象析构时,文件和sockets会自动关闭,试图将文件对象的生命周期和文件的状态绑定在一起的想法, 都是不现实的。因为有如下原因: + +1. 没有任何方法可以确保运行环境会真正的执行文件的析构. 不同的Python实现采用不同的内存管理技术, 比如延时垃圾处理机制. 延时垃圾处理机制可能会导致对象生命周期被任意无限制的延长。 +2. 对于文件意外的引用,会导致对于文件的持有时间超出预期(比如对于异常的跟踪, 包含有全局变量等)。 + + + +[1.15.2](<#1.15.2>) **【推荐】** 推荐使用 `with` 语句管理文件。 + +```python +with open("hello.txt") as hello_file: + for line in hello_file: + print(line) +``` + +对于不支持使用`with`语句的类似文件的对象,使用`contextlib.closing()`: + +```python +import contextlib + +with contextlib.closing(urllib.urlopen("http://www.python.org/")) as front_page: + for line in front_page: + print(line) +``` + +Legacy AppEngine 中Python 2.5的代码如使用`with`语句, 需要添加 `from __future__ import with_statement`. + + + + + + + +### 1.16 访问控制 + +> 在Python中,对于琐碎又不太重要的访问函数, 应该直接使用公有变量来取代它们,这样可以避免额外的函数调用开销。 + 当添加更多功能时,也可以用属性(property)来保持语法的一致性。 + +[1.16.1](<#1.16.1>) **【推荐】** 如果访问属性后需要复杂的逻辑处理,或者变量的访问开销很显著, 那么应该使用像 `get_foo()` 和 `set_foo()` 这样的函数调用。 +如果之前的代码行为已经通过属性(property)访问,那么就不要将新的访问函数与属性绑定。 否则,任何试图通过老方法访问变量的代码就没法运行,使用者也就会意识到复杂性发生了变化。 (如果可以重构这个代码是最好的了) + + + + + + + + +### 1.17 Main + +> 即使是一个打算被用作脚本的文件, 也应该是可导入的。 + 并且简单的导入不应该导致这个脚本的主功能(main functionality)被执行,这是一种副作用。 + 主功能应该放在一个main()函数中。 + +[1.17.1](<#1.17.1>) **【必须】** 所有的文件都应该可以被导入。 对不需要作为程序入口地方添加 `if __name__ == '__main__' `。 + +在Python中,pydoc以及单元测试要求模块必须是可导入的。 你的代码应该在执行主程序前总是检查 `if __name__ == '__main__' `, 这样当模块被导入时主程序就不会被执行。 +所有的顶级代码在模块导入时都会被执行。 要小心不要去调用函数,创建对象,或者执行那些不应该在使用pydoc时执行的操作。 + + + +***正确示范*** + +```python +def main(): + ... + +if __name__ == '__main__': + main() +``` + + + + + + +### 1.18 命名 + +> module_name, package_name, ClassName, method_name, ExceptionName, function_name, GLOBAL_VAR_NAME, instance_var_name, function_parameter_name, local_var_name. + +应该避免的名称: + +1. 单字符名称,除了计数器和迭代器。 +2. 包/模块名中的连字符(-)。 +3. 双下划线开头并结尾的名称(Python保留,例如__init__)。 + +[1.18.1](<#1.18.1>) **【推荐】** 命名约定规则如下: pylint:`invalid-name`. + +1. 所谓`内部(Internal)`表示仅模块内可用, 或者, 在类内是保护或私有的。 +2. 用单下划线`(_)`开头表示模块变量或函数是protected的(使用 `from module import *` 时不会包含)。 +3. 用双下划线`(__)`开头的实例变量或方法表示类内私有。 +4. 将相关的类和顶级函数放在同一个模块里。不像Java,没必要限制一个类一个模块。 +5. 对类名使用大写字母开头的单词(如CapWords, 即Pascal风格),但是模块名应该用小写加下划线的方式(如lower_with_under.py)。尽管已经有很多现存的模块使用类似于CapWords.py这样的命名,但现在已经不鼓励这样做, 因为如果模块名碰巧和类名一致,这会让人困扰。 + +Python之父Guido推荐的规范: + +| Type | Public | Internal | +| ---------- | -------------------- | -------------------- | +| Modules | lower_with_under | \_lower\_with\_under | +| Packages | lower\_with\_under | | +| Classes | CapWords | \_CapWords | +| Exceptions | CapWords | | +| Functions | lower\_with\_under() | \_lower_with_under() | +| Global/Class Constants | CAPS\_WITH\_UNDER | \_CAPS\_WITH\_UNDER | +| Global/Class Variables | lower\_with\_under | \_lower\_with\_under | +| Instance Variables | lower\_with\_under | \_lower\_with\_under (protected) or \_\_lower\_with_under (private) | +| Method Names | lower\_with\_under() | \_lower\_with_under() (protected) or \_\_lower_with_under() (private) | +| Function/Method Parameters | lower\_with\_under | | +| Local Variables | lower\_with\_under | | + + + + + +## 二、编码规范 + + + + + +### 2.1 三目运算符 + + +[2.1.1](<#2.1.1>) **【必须】** 三目操作符判断,python 不支持三目运算符,但可使用如下方式,禁止使用复杂难懂的逻辑判断。 + + + + +***正确示范*** + +```python +x = a if a >= b else b +``` + + +***错误示范*** + +```python +x = a >= b and a or b +``` + + + + + + +### 2.2 None 条件的判断 + + +[2.2.1](<#2.2.1>) **【必须】** 为提升可读性,在判断条件中应使用 `is not`,而不使用 `not ... is`。 pycodestyle:`E714 test for object identity should be 'is not'`. + + + + +***正确示范*** + +```python +if foo is not None: +``` + + +***错误示范*** + +```python +if not foo is None: +``` + + + + + + +### 2.3 lambda匿名函数 + + +[2.3.1](<#2.3.1>) **【必须】** 使用 def 定义简短函数而不是使用 lambda。 pycodestyle:`E731 do not assign a lambda expression, use a def`. + +使用def的方式有助于在trackbacks中打印有效的类型信息,明确使用`f`函数而不是一个lambda的调用。 + + +***正确示范*** + +```python +def f(x): + return 2 * x +``` + + +***错误示范*** + +```python +f = lambda x: 2 * x +``` + + + + + + +### 2.4 异常 + + +[2.4.1](<#2.4.1>) **【必须】** 异常类继承自 `Exception`,而不是 `BaseException`。 + + + + +[2.4.2](<#2.4.2>) **【必须】** 使用新版本抛出异常的方式,禁止使用废弃的方式。 pycodestyle:`W602 deprecated form of raising exception`. + + + + +***正确示范*** + +```python +raise ValueError('message') +``` + + +***错误示范*** + +```python +raise ValueError, 'message' +``` + + +[2.4.3](<#2.4.3>) **【必须】** 捕获异常时,需要指明具体异常,而不是捕获所有异常。 除非已经在当前线程的最外层(记得还是要打印一条traceback)。 pylint:`broad-except`, `bare-except`. + + + + +***正确示范*** + +```python +try: + import platform_specific_module +except ImportError: + platform_specific_module = None + +try: + do_something() +except Exception as ex: # pylint: disable=broad-except + log.exception(ex) # 应将错误堆栈打印到日志文件中,以供后续排查。 + handle_exception_or_not() # 除打印日志外,还可以进一步处理如清理资源等,可选。 +``` + + +***错误示范*** + +```python +try: + import platform_specific_module +except Exception: # broad-except + platform_specific_module = None + +try: + do_something() +except Exception: # 框架等未明确异常场景,建议增加 traceback 打印 + pass +``` + + +[2.4.4](<#2.4.4>) **【推荐】** 建议在代码中用异常替代函数的错误返回码。 + + + + +***正确示范*** + +```python +def write_data(): + if check_file_exist(): + do_something() + else: + raise FileNotExist() +``` + + +***错误示范*** + +```python +def write_data(): + if check_file_exist(): + do_something() + return 0 + else: + return FILE_NOT_EXIST +``` + + +[2.4.5](<#2.4.5>) **【推荐】** 在 `except` 子句中重新抛出原有异常时,不能用 `raise ex`,而是用 `raise`。 + + + + +***正确示范*** + +```python +try: + raise MyException() +except MyException as ex: + try_handle_exception() + raise # 可以保留原始的 traceback + + +try: + raise MyException() +except MyException as ex: + log.exception(ex) + raise AnotherException(str(ex)) # 允许的,建议保留好之前的异常栈信息,用于定位问题 +``` + + +***错误示范*** + +```python +try: + raise MyException() +except MyException as ex: + try_handle_exception() + raise ex # 异常栈信息从这里开始,原始的raise异常栈信息消息 +``` + + +[2.4.6](<#2.4.6>) **【推荐】** 所有 `try`/`except` 子句的代码要尽可的少,以免屏蔽其他的错误。 + + + + +***正确示范*** + +```python +try: + value = collection[key] +except KeyError: + return key_not_found(key) +else: + return handle_value(value) +``` + + +***错误示范*** + +```python +try: + # 范围太广 + return handle_value(collection[key]) +except KeyError: + # 会捕捉到 handle_value() 中的 KeyError + return key_not_found(key) +``` + + + + + + +### 2.5 条件表达式 + + +[2.5.1](<#2.5.1>) **【推荐】** 函数或者方法在没有返回时要明确返回`None`。 pylint:`inconsistent-return-statements`. + + + + +***正确示范*** + +```python +def foo(x): + if x >= 0: + return math.sqrt(x) + else: + return None + +def bar(x): + if x < 0: + return None + return math.sqrt(x) +``` + + +***错误示范*** + +```python +def foo(x): + if x >= 0: + return math.sqrt(x) + +def bar(x): + if x < 0: + return + return math.sqrt(x) +``` + + +[2.5.2](<#2.5.2>) **【推荐】** 对于未知的条件分支或者不应该进入的分支,建议抛出异常,而不是返回一个值(比如说`None` 或`False`)。 + + + + +***正确示范*** + +```python +def f(x): + if x in ('SUCCESS',): + return True + else: + raise MyException() # 如果一定不会走到的条件,可以增加异常,防止将来未知的语句执行。 +``` + + +***错误示范*** + +```python +def f(x): + if x in ('SUCCESS',): + return True + return None +``` + + +[2.5.3](<#2.5.3>) **【可选】** `if` 与 `else` 尽量一起出现,而不是全部都是`if`子句。 + + + + +***正确示范*** + +```python +if condition: + do_something() +else: + # 增加说明注释 + pass + +if condition: + do_something() +# 这里增加注释说明为什么不用写else子句 +# else: +# pass +``` + + +***错误示范*** + +```python +if condition: + do_something() +if another_condition: # 不能确定是否笔误为 elif ,还是开启全新一个if条件 + do_another_something() +else: + do_else_something() +``` + + + + + + +### 2.6 True/False 布尔运算 + + +[2.6.1](<#2.6.1>) **【必须】** 不要用 `==` 与 `True`、 `False` 进行布尔运算。 pylint:`singleton-comparison`. + + + + +***正确示范*** + +```python +if greeting: + pass +``` + + +***错误示范*** + +```python +if greeting == True: + pass + +if greeting is True: # Worse + pass +``` + + +[2.6.2](<#2.6.2>) **【必须】** 对序列(字符串、列表 、元组),空序列为 false 的情况。 pylint:`len-as-condition`. + + + + +***正确示范*** + +```python +if not seq: + pass + +if seq: + pass +``` + + +***错误示范*** + +```python +if len(seq): + pass + +if not len(seq): + pass +``` + + + + + + +### 2.7 列表推导式 + + +[2.7.1](<#2.7.1>) **【必须】** 禁止超过1个for语句或过滤器表达式,否则使用传统`for`循环语句替代。 + + + + +***正确示范*** + +```python +number_list = [1, 2, 3, 10, 20, 55] +odd = [i for i in number_list if i % 2 == 1] + +result = [] +for x in range(10): + for y in range(5): + if x * y > 10: + result.append((x, y)) +``` + + +***错误示范*** + +```python +result = [(x, y) for x in range(10) for y in range(5) if x * y > 10] # for 语句 +``` + + +[2.7.2](<#2.7.2>) **【推荐】** 列表推导式适用于简单场景。 如果语句过长,每个部分应该单独置于一行: 映射表达式, for语句, 过滤器表达式。 + + + + +***正确示范*** + +```python +fizzbuzz = [] +for n in range(100): + if n % 3 == 0 and n % 5 == 0: + fizzbuzz.append(f'fizzbuzz {n}') + elif n % 3 == 0: + fizzbuzz.append(f'fizz {n}') + elif n % 5 == 0: + fizzbuzz.append(f'buzz {n}') + else: + fizzbuzz.append(n) + + +for n in range(1, 11): + print(n) +``` + + +***错误示范*** + +```python +# 条件过于复杂,应该采用for语句展开 +fizzbuzz = [ + f'fizzbuzz {n}' if n % 3 == 0 and n % 5 == 0 + else f'fizz {n}' if n % 3 == 0 + else f'buzz {n}' if n % 5 == 0 + else n + for n in range(100) +] + + +[print(n) for n in range(1, 11)] # 无返回值 +``` + + + + + + +### 2.8 函数 + + +[2.8.1](<#2.8.1>) **【必须】** 模块内部禁止定义重复函数声明。 pylint:`function-redefined`. + +禁止重复的函数定义。 + + + +***错误示范*** + +```python +def get_x(x): + return x + +def get_x(x): # 模块内重复定义 + return x +``` + + +[2.8.2](<#2.8.2>) **【必须】** 函数参数中,不允许出现可变类型变量作为默认值。 pylint:`dangerous-default-value`. + + + + +***正确示范*** + +```python +def f(x=0, y=None, z=None): + if y is None: + y = [] + if z is None: + z = {} +``` + + +***错误示范*** + +```python +def f(x=0, y=[], z={}): + pass + +def f(a, b=time.time()): + pass +``` + + + + + + +### 2.9 变量 + + +[2.9.1](<#2.9.1>) **【必须】** 禁止定义了变量却不使用它。 pylint:`unused-variable`. + +在代码里到处定义变量却没有使用它,不完整的代码结构看起来像是个代码错误。 即使没有使用,但是定义变量仍然需要消耗资源,并且对阅读代码的人也会造成困惑,不知道这些变量是要做什么的。 + + + +***正确示范*** + +```python +def get_x_plus_y(x, y): + return x + y +``` + + +***错误示范*** + +```python +some_unused_var = 42 + +# 定义了变量不意味着就是使用了 +y = 10 +y = 5 + +# 对自身的操作并不意味着使用了 +z = 0 +z = z + 1 + +# 未使用的函数参数 +def get_x(x, y): + return x +``` + + +[2.9.2](<#2.9.2>) **【推荐】** 使用双下划线 `__` 来代表不需要的变量,单下划线 `_` 容易与 `gettext()` 函数的别名冲突。 + + + + +***正确示范*** + +```python +path = '/tmp/python/foobar.txt' +dir_name, __ = os.path.split(path) +``` + + + + +## 工具与配置 + +### flake8 + +[`flake8`](https://flake8.pycqa.org/) 是一个结合了 pycodestyle,pyflakes,mccabe 检查 Python 代码规范的工具。 + + +使用方法: + +```bash +flake8 {source_file_or_directory} +``` + +在项目中创建 `setup.cfg` 或者 `tox.ini` 或者 `.flake8` 文件,添加 `[flake8]` 部分。 + +推荐的配置文件如下: + +```ini +[flake8] +ignore = + ;W503 line break before binary operator + W503, + ;E203 whitespace before ':' + E203, + +; exclude file +exclude = + .tox, + .git, + __pycache__, + build, + dist, + *.pyc, + *.egg-info, + .cache, + .eggs + +max-line-length = 120 +``` + +如果需要屏蔽告警可以增加行内注释 `# noqa`,例如: + +```python +example = lambda: 'example' # noqa: E731 +``` + +### pylint + +[`pylint`](https://www.pylint.org/) 是一个能够检查编码质量、编码规范的工具。 + +配置项较多,单独一个配置文件配置,详情可查阅配置文件:`.pylintrc` + +使用方法: + +```bash +pylint {source_file_or_directory} +``` + +如果遇到一些实际情况与代码冲突的,可以在行内禁用相关检查,例如 : + +```python +try: + do_something() +except Exception as ex: # pylint: disable=broad-except + pass +``` + +如果需要对多行的进行禁用规则,可以配套使用 `# pylint: disable=具体错误码`/`# pylint: enable=具体错误码`。 + +```python +# pylint: disable=invalid-name +这里的代码块会被忽略相关的告警 +app = Flask(__name__) +# pylint: enable=invalid-name +``` + + +### black + +[`black`](https://github.com/psf/black) 是一个官方的 Python 代码格式化工具。 + +使用方法: + +```bash +black {source_file_or_directory} +``` + +如果不想格式化部分代码,可以配套使用 `# fmt: off`/`# fmt: on` 临时关闭格式化。 + +```python +# fmt: off +在这的代码不会被格式化 +# fmt: on +``` + +### EditorConfig + +EditorConfig 可以帮助开发同一项目下的跨多 IDE 的开发人员保持一致编码风格。 + +在项目的根目录下放置 `.editorconfig` 文件,可以让编辑器规范文件对格式。参考配置如下: + +```ini +# https://editorconfig.org + +root = true + +[*] +indent_style = space +indent_size = 4 +trim_trailing_whitespace = true +insert_final_newline = true +charset = utf-8 +end_of_line = lf + +[*.py] +max_line_length = 120 + +[*.bat] +indent_style = tab +end_of_line = crlf + +[LICENSE] +insert_final_newline = false + +[Makefile] +indent_style = tab +``` + +支持常见的 IDE ,配置说明及 IDE 的支持情况可参考官网 [editorconfig.org](https://editorconfig.org/)。 \ No newline at end of file