命名一直是程序员最烦恼的事情之一,一个好的命名可以让一段代码看起来可读性更强,后续维护的人员也会更轻松。因此,在团队中统一使用同一套命名规范是相当有必要的。
今天,猿妹要和大家分享一份命名宝典,专门帮助程序员如何命名,这个项目介绍了命名时需要考虑的数个要点,旨在帮你解决命名困难的问题,教你如何便捷、轻松地进行命名,这个项目就叫——naming-cheatsheet。
naming-cheatsheet已经在Github上标星 7.9K,累计分支 386 个(Github地址:https://github.com/kettanaito/naming-cheatsheet)
这些命名规则适用于任何编程语言,创建者以JavaScript为例演示,一起来看看吧:
英语命名
在命名变量和函数名时用英文名称命名:
/* Bad */
const primerNombre = 'Gustavo'
const amigos = ['Kate', 'John']
/* Good */
const firstName = 'Gustavo'
const friends = ['Kate', 'John']
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
不管你喜欢与否,英语是编程中的主导语言,所有编程语言的语法都是用英语编写的,还有无数的文档和教学资料也是英文,通过英语编写代码,可以极大地增加代码的凝聚力。
约定命名
选择一套命名规范并遵循它,在团队中保持命名的一致性,它可以是camelCase、PascalCase、snake_case或其他任何东西。许多编程语言在命名约定方面都有自己的传统,你可以查看自己的编程语言文档或者学习一些Github上流行的知识库。
/* Bad */
const page_count = 5
const shouldUpdate = true
/* Good */
const pageCount = 5
const shouldUpdate = true
/* Good as well */
const page_count = 5
const should_update = true
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
S-I-D命名原则
名称必须简短、直观和描述性:
- 短:输入一个名称一定不要花太长时间,因此一定要简短
- 直观:名称读起来一定要直观,尽可能贴近日常用语
- 描述性:名称必须可以用最有效的方式反映它的作用
/* Bad */
const a = 5 // "a" could mean anything
const isPaginatable = a > 10 // "Paginatable" sounds extremely unnatural
const shouldPaginatize = a > 10 // Made up verbs are so much fun!
/* Good */
const postCount = 5
const hasPagination = postCount > 10
const shouldPaginate = postCount > 10 // alternatively
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
避免过度的简写
不要使用缩写,它们只会降低代码的可读性,找到一个简短的可读的名称可能会很难,但即便如此也别使用简写。
/* Bad */
const onItmClk = () => {}
/* Good */
const onItemClick = () => {}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
避免重复命名
上下文的名称不应该重复
class MenuItem {
/* Method name duplicates the context (which is "MenuItem") */
handleMenuItemClick = (event) => { ... }
/* Reads nicely as `MenuItem.handleClick()` */
handleClick = (event) => { ... }
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
反映预期结果
变量或函数的命名应该做到能够反映预期的结果。
/* Bad */
const isEnabled = itemCount > 3
return <Button disabled={!isEnabled} />
/* Good */
const isDisabled = itemCount <= 3
return <Button disabled={isDisabled} />
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
以上就是命名的6大原则,除此之外,创建者还介绍了命名模式,诸如A/HC/LC模式、动作、前缀、单复数等模式,感兴趣的不妨自己去学习一下吧。