约定命名
选择一套命名规范并遵循它,在团队中保持命名的一致性,它可以是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
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
避免过度的简写
不要使用缩写,它们只会降低代码的可读性,找到一个简短的可读的名称可能会很难,但即便如此也别使用简写。
- /* Bad */
- const onItmClk = () => {}
- /* Good */
- const onItemClick = () => {}
避免重复命名
上下文的名称不应该重复
- class MenuItem {
- /* Method name duplicates the context (which is "MenuItem") */
- handleMenuItemClick = (event) => { … }
- /* Reads nicely as `MenuItem.handleClick()` */
- handleClick = (event) => { … }
- }
反映预期结果
变量或函数的命名应该做到能够反映预期的结果。
- /* Bad */
- const isEnabled = itemCount > 3
- return <Button disabled={!isEnabled} />
- /* Good */
- const isDisabled = itemCount <= 3
- return <Button disabled={isDisabled} />
以上就是命名的6大原则,除此之外,创建者还介绍了命名模式,诸如A/HC/LC模式、动作、前缀、单复数等模式,感兴趣的不妨自己去学习一下吧。