Github标星7.9K!程序员专属的法器来了

约定命名

选择一套命名规范并遵循它,在团队中保持命名的一致性,它可以是camelCase、PascalCase、snake_case或其他任何东西。许多编程语言在命名约定方面都有自己的传统,你可以查看自己的编程语言文档或者学习一些Github上流行的知识库。


  1. /* Bad */ 
  2.  
  3. const page_count = 5 
  4.  
  5. const shouldUpdate = true 
  6.  
  7. /* Good */ 
  8.  
  9. const pageCount = 5 
  10.  
  11. const shouldUpdate = true 
  12.  
  13. /* Good as well */ 
  14.  
  15. const page_count = 5 
  16.  
  17. const should_update = true 

S-I-D命名原则

名称必须简短、直观和描述性:

  • 短:输入一个名称一定不要花太长时间,因此一定要简短
  • 直观:名称读起来一定要直观,尽可能贴近日常用语
  • 描述性:名称必须可以用最有效的方式反映它的作用

  1. /* Bad */ 
  2.  
  3. const a = 5 // "a" could mean anything 
  4.  
  5. const isPaginatable = a > 10 // "Paginatable" sounds extremely unnatural 
  6.  
  7. const shouldPaginatize = a > 10 // Made up verbs are so much fun! 
  8.  
  9. /* Good */ 
  10.  
  11. const postCount = 5 
  12.  
  13. const hasPagination = postCount > 10 
  14.  
  15. const shouldPaginate = postCount > 10 // alternatively 

避免过度的简写

不要使用缩写,它们只会降低代码的可读性,找到一个简短的可读的名称可能会很难,但即便如此也别使用简写。


  1. /* Bad */ 
  2.  
  3. const onItmClk = () => {} 
  4.  
  5. /* Good */ 
  6.  
  7. const onItemClick = () => {} 

避免重复命名

上下文的名称不应该重复


  1. class MenuItem { 
  2.  
  3. /* Method name duplicates the context (which is "MenuItem") */ 
  4.  
  5. handleMenuItemClick = (event) => { … } 
  6.  
  7. /* Reads nicely as `MenuItem.handleClick()` */ 
  8.  
  9. handleClick = (event) => { … } 
  10.  

反映预期结果

变量或函数的命名应该做到能够反映预期的结果。


  1. /* Bad */ 
  2.  
  3. const isEnabled = itemCount > 3 
  4.  
  5. return <Button disabled={!isEnabled} /> 
  6.  
  7. /* Good */ 
  8.  
  9. const isDisabled = itemCount <= 3 
  10.  
  11. return <Button disabled={isDisabled} /> 

以上就是命名的6大原则,除此之外,创建者还介绍了命名模式,诸如A/HC/LC模式、动作、前缀、单复数等模式,感兴趣的不妨自己去学习一下吧。

【声明】:芜湖站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

相关文章