Skip to content

编写可阅读的代码 #6

@5201314999

Description

@5201314999

编写可阅读的代码(Writing Readable Code)

背景

  1. 这周参与会员等级需求,改动了wechat 的一些代码。
  2. 前阵子看了一些代码规范的资料。

可阅读的代码目标

有一句话是说: �Write code that minimizes the time it would take someone to understand it .

几方面入手提高

  1. 代码格式化
    代码格式化的工具其实目前还是挺多的,基础的格式化有prettier (支持对空格,拖尾分号),eslint 。目前会员小程序是采用vascode 配置

  2. 注释

大部分代码其实是不需要注释的

https://www.youtube.com/watch?v=yhF7OmuIILc

 

对于特殊业务和特殊情况还是需要说明的。对于不同团队以及不同时期的人来说。对于整体部分的注释可以相当于文章的章节或着目录说明。

例如浏览器兼容性,一些妥协性的实现,后续需要更新,由于上线时间赶,暂时先使用什么方式,或者此方案非最佳,有利于后续的重构。

``
不好的注释:

  1. 重复描述代码已经能说明的事。
  2. 不更新注释
  3. 直接注释部分代码,又不说明意图,会让后面的维护人员赶到困惑。

还有一种情况是当你的实现方式来源于网上某篇文章的时候可以把链接放上去,这样当过段时间你在来看代码的时候不至于会觉得奇怪自己为什么会写出这种代码。

  1. 命名

常见的命名

validate�Form getErrors ,is�Valid , checkData getToken createToken fetchToken .

shouldShow�Dialog. is�Initied , has�Checked , canLoadMore 显示boolean 值的。

4

参考资料:

  1. The Art of Code Comments - Sarah Drasner | JSConf Hawaii 2020
  2. �Writing readable code
  3. https://www.youtube.com/watch?v=HcijbAI4eB0

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions