编写代码的最佳实践

2025-08-16 15:16:00
丁国栋
原创 11
摘要:本文记录编写代码的最佳实践,持续更新中。

---

《编写可读代码的艺术》(The Art of Readable Code: Simple and Practical Techniques for Writing Better Code)作者是 Dustin Boswell 和 Trevor Foucher。

表面层次的改进

  • 代码应当易于理解。

    • 这是本书的核心原则,所有技巧都围绕这一目标展开。
  • 关键思想是代码的写法应当使别人理解它所需的时间最小化。

    • 可读性基本定理:代码的写法应当使别人理解它所需的时间最小化。
  • 把信息装到名字里,选择专业的词,避免泛泛的名字。

    • 例如,用 FetchPage() 而不是 GetData(),因为前者更精确地描述了行为。
  • 名字应当尽可能精确。

    • 避免模糊的名字,比如 datainfo,而应该用 userProfilerequestCount 等。
  • 名字的长短应该与其作用域大小相对应。

    • 短名字适合小作用域(如循环变量 i),长名字适合大作用域(如全局配置 maxConnectionsPerServer)。
  • 使用格式、一致性和惯用法来传递意义。

    • 例如,类名用 PascalCase,变量名用 camelCase,常量用 UPPER_CASE,以增强可读性。
  • 写注释的目的是尽量帮助读者了解得和作者一样多。

    • 注释不应重复代码,而应解释代码背后的意图或特殊情况。
  • 注释应当说明“做什么”“为什么”而不是“怎么做”。

    • 例如,// 检查缓存是否过期(TTL 10秒)// 检查 currentTime - lastUpdate > 10 更好。
  • 为代码中的瑕疵写注释,如标记“TODO”“FIXME”。

    • 这样可以让后续开发者知道哪些地方需要改进或修复。

简化循环和逻辑

  • 把控制流变得易读,条件循环语句应该遵循自然语言的习惯。

    • 例如,if (isReady) { ... }if (readyFlag == true) { ... } 更自然。
  • 拆分超长表达式,引入解释变量。

    • 例如,把 if (user.age > 18 && user.country == "US" && !user.isBanned) 拆分成 isAdultInUSisNotBanned 两个变量。
  • 变量与可读性,减少变量,缩小变量的作用域。

    • 避免不必要的中间变量,比如 tempresult,除非它们能提升可读性。
  • 尽量少写嵌套代码,提前返回减少嵌套。

    • 例如,用 if (!isValid) return; 代替深层嵌套的 if-else

重新组织代码

  • 抽取不相关的子问题,将代码拆分为更小的函数。

    • 例如,把日志记录、数据校验等逻辑单独封装成函数。
  • 一次只做一件事,一个函数应该只完成一个任务。

    • 例如,LoadUserData() 不应该同时负责数据解析和缓存更新。
  • 把想法变成代码,用自然语言描述逻辑,再翻译成代码。

    • 先写伪代码,再逐步细化,有助于理清思路。
  • 减少代码依赖,让代码更模块化。

    • 避免全局变量,尽量让函数只依赖输入参数。

精选话题

  • 测试与可读性,测试代码应当清晰易读。

    • 测试代码的可读性甚至比业务代码更重要,因为它直接影响维护成本。
  • 测试应当简洁明了,避免重复代码。

    • 使用测试工具(如 setup()teardown())减少重复逻辑。
  • 代码应当易于测试,设计良好的代码更容易测试。

    • 例如,避免紧耦合,让函数可以独立测试。
  • 代码应当自文档化,减少对注释的依赖。

    • 良好的命名和结构可以让代码不言自明。

更大的层面

  • 设计良好的接口,接口应当简单直观。

    • 例如,SaveToFile(filename)Save(data, format, location) 更易用。
  • 避免过度设计,代码应当只解决当前问题。

    • 不要为了“未来可能的需求”增加不必要的复杂性。
  • 代码应当易于扩展,但不要预先增加不必要的复杂性。

    • 例如,用插件模式而不是硬编码所有逻辑。
  • 代码应当符合团队规范,保持一致性。

    • 即使个人有偏好,也应遵循团队约定的风格。

总结

  • 可读性基本定理:代码的写法应当使别人理解它所需的时间最小化。

    • 这是衡量代码质量的黄金标准。
  • 代码应当像故事一样流畅,让读者轻松跟随作者的思路。

    • 良好的代码结构能让阅读者自然理解逻辑流程。
  • 持续改进代码,重构是提升可读性的重要手段。

    • 代码不是写完就结束了,要不断优化可读性。

---

使用 GPG 签名


➜  zsite git:(master) ✗ git config --get user.name 
DingGuodong
➜  zsite git:(master) ✗ git config --get user.email 
dingguodong@thedf.cc
➜  zsite git:(master) ✗ gpg --list-secret-keys --keyid-format=long
gpg: directory '/root/.gnupg' created
gpg: keybox '/root/.gnupg/pubring.kbx' created
gpg: /root/.gnupg/trustdb.gpg: trustdb created
➜  zsite git:(master) ✗ gpg --full-generate-key
gpg (GnuPG) 2.2.40; Copyright (C) 2022 g10 Code GmbH
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Please select what kind of key you want:
   (1) RSA and RSA (default)
   (2) DSA and Elgamal
   (3) DSA (sign only)
   (4) RSA (sign only)
  (14) Existing key from card
Your selection? 
RSA keys may be between 1024 and 4096 bits long.
What keysize do you want? (3072) 
Requested keysize is 3072 bits
Please specify how long the key should be valid.
         0 = key does not expire
      <n>  = key expires in n days
      <n>w = key expires in n weeks
      <n>m = key expires in n months
      <n>y = key expires in n years
Key is valid for? (0) 
Key does not expire at all
Is this correct? (y/N) y
GnuPG needs to construct a user ID to identify your key.
Real name: DingGuodong
Email address: dingguodong@thedf.cc
Comment: Created at 20250815 @thedf.cc
You selected this USER-ID:
    "DingGuodong (Created at 20250815 @thedf.cc) <dingguodong@thedf.cc>"
Change (N)ame, (C)omment, (E)mail or (O)kay/(Q)uit? O
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
We need to generate a lot of random bytes. It is a good idea to perform
some other action (type on the keyboard, move the mouse, utilize the
disks) during the prime generation; this gives the random number
generator a better chance to gain enough entropy.
gpg: directory '/root/.gnupg/openpgp-revocs.d' created
gpg: revocation certificate stored as '/root/.gnupg/openpgp-revocs.d/C285DC10B1766467354EB021AD53FFF0DD0D5FAA.rev'
public and secret key created and signed.
pub   rsa3072 2025-08-15 [SC]
      C285DC10B1766467354EB021AD53FFF0DD0D5FAA
uid                      DingGuodong (Created at 20250815 @thedf.cc) <dingguodong@thedf.cc>
sub   rsa3072 2025-08-15 [E]
➜  zsite git:(master) ✗ 


--

发表评论
博客分类