The Matrix: Writing Code That Doesn't Need Comments

The Matrix: Writing Code That Doesn’t Need Comments

黑客帝国:编写无需注释的代码

The Quest Begins (The “Why”)

探索的起点(“为什么”)

I still remember the first time I opened a legacy codebase and felt like I’d stepped into a dark dungeon without a torch. The file was a single 800‑line function called processData. Inside, variables bore names like tmp, x, flag, and comments that tried to explain every line: 我还记得第一次打开遗留代码库时的情景,感觉就像没带火把走进了一座黑暗的地牢。那个文件是一个长达 800 行的函数,名叫 processData。里面变量的名字全是 tmpxflag 之类的,注释则试图解释每一行代码:

// TODO: refactor this mess
function processData(input) {
  let r = []; // result array
  for (let i = 0; i < input.length; i++) { // loop over items
    if (input[i] > 10) { // if value greater than threshold
      let v = input[i] * 2; // double it
      if (v % 2 === 0) { // if even
        r.push(v); // add to result
      }
    }
  }
  return r;
}

I spent three hours tracing why a certain edge case produced an empty array, only to discover the comment “if value greater than threshold” was outdated—the threshold had changed to 12 in a later commit, but the comment never got updated. The code lied, the comments misled, and I felt like a hero who’d just swung at a shadow. That frustration sparked a question: What if we could write code so clear that comments became unnecessary? Not because we’re lazy, but because the code itself tells the story. 我花了三个小时去追踪为什么某个边界情况会产生空数组,结果发现“如果值大于阈值”这条注释已经过时了——在后来的提交中,阈值已经改成了 12,但注释却没更新。代码在撒谎,注释在误导,我感觉自己像个对着影子挥剑的英雄。这种挫败感引发了一个问题:如果我们能写出足够清晰的代码,让注释变得多余,会怎样?这并非因为我们懒惰,而是因为代码本身就能讲述它的逻辑。

The Revelation (The Insight)

启示(洞察)

The treasure I uncovered wasn’t a new framework or a slick library—it was a mindset shift: make the code self‑documenting through intention‑revealing names and small, focused functions. When a variable, function, or class name reads like a sentence, the reader can infer what’s happening without a side note. Think of it like reading a well‑written novel. You don’t need footnotes to understand that “She opened the door and stepped into the rain” means she’s going outside. The same principle applies to code: if you name a function filterValuesAboveThreshold, the intent is obvious. 我发现的宝藏不是什么新框架或炫酷的库,而是一种思维方式的转变:通过表达意图的命名和短小精悍的函数,让代码实现“自文档化”。当变量、函数或类名读起来像句子一样时,读者无需旁注就能推断出发生了什么。把它想象成读一本优秀的小说,你不需要脚注就能明白“她打开门走进雨中”意味着她要出门。同样的原则适用于代码:如果你将函数命名为 filterValuesAboveThreshold,其意图就一目了然。

Why does this matter? Because comments decay. They become outdated, they get ignored, and they add noise. Self‑explanatory code, on the other hand, stays accurate as long as the name stays accurate. It also forces you to think about the why behind each piece, which often leads to better design decisions. 为什么这很重要?因为注释会“腐烂”。它们会过时、被忽略,并增加干扰。相反,自解释代码只要名称准确,它本身就是准确的。它还迫使你思考每一部分背后的原因,这通常会带来更好的设计决策。

Wielding the Power (Code & Examples)

运用力量(代码与示例)

Let’s see the transformation in action. Below is a typical “before” snippet that leans heavily on comments to explain what’s happening. 让我们看看这种转变的实际效果。下面是一个典型的“修改前”代码片段,它严重依赖注释来解释逻辑。

Before – Comment‑Dependent Code 修改前 – 依赖注释的代码

# Calculate the total price for a shopping cart
def calc_total(items):
    total = 0 # start with zero
    for i in items: # iterate over each item
        if i['discount'] > 0: # if the item has a discount
            price = i['price'] * (1 - i['discount']) # apply discount
        else:
            price = i['price'] # no discount
        total += price # add to running total
    # apply tax if total exceeds $100
    if total > 100:
        total *= 1.08 # add 8% tax
    return total

The comments are helpful, but they’re also a maintenance liability. Imagine the tax rate changes to 7.5% or the discount logic becomes more complex—now you have to hunt down every comment and keep it in sync. 这些注释很有帮助,但它们也是维护负担。想象一下,如果税率变为 7.5%,或者折扣逻辑变得更复杂——你现在必须找出每一条相关注释并保持同步。

After – Self‑Explanatory Code 修改后 – 自解释代码

def calculate_cart_total(items):
    subtotal = sum(_apply_discount(item) for item in items)
    return _apply_tax_if_needed(subtotal)

def _apply_discount(item):
    if item['discount'] > 0:
        return item['price'] * (1 - item['discount'])
    return item['price']

def _apply_tax_if_needed(amount):
    if amount > 100:
        return amount * 1.08 # 8% tax
    return amount

What changed? Function names read like sentences: calculate_cart_total, _apply_discount, _apply_tax_if_needed. Variables (subtotal, amount) convey their role at a glance. The logic is split into tiny, pure functions that each do one thing—making the flow obvious without a single comment. If the tax rule changes, you only touch _apply_tax_if_needed. If discount calculations become more elaborate, you edit _apply_discount. The main function stays a clear, high‑level overview: “get the subtotal, then maybe add tax.” 发生了什么变化?函数名读起来像句子:calculate_cart_total_apply_discount_apply_tax_if_needed。变量(subtotalamount)一眼就能看出其作用。逻辑被拆分为微小、纯粹的函数,每个函数只做一件事——无需任何注释,流程就显而易见。如果税收规则改变,你只需修改 _apply_tax_if_needed;如果折扣计算变得复杂,你只需编辑 _apply_discount。主函数保持清晰的高层概览:“获取小计,然后根据需要加税。”

Common Traps to Avoid

常见的陷阱

  • Over‑abbreviating namescalcTot, itm, disc. Short names save a few keystrokes but cost hours of confusion later.
  • 过度缩写名称calcTotitmdisc。短名称节省了几个按键,但以后会造成数小时的困惑。
  • Leaving stale comments – A comment that contradicts the code is worse than no comment at all. If you feel compelled to comment, ask yourself: “Can I rename something to make this obvious?”
  • 留下过时的注释 – 与代码相矛盾的注释比没有注释更糟糕。如果你觉得必须写注释,问问自己:“我能通过重命名让它变得显而易见吗?”
  • Creating god‑functions – Even with perfect names, a 200‑line function is hard to follow. Break it down; each piece should be a single, named intention.
  • 创建“上帝函数” – 即使命名完美,200 行的函数也很难阅读。拆解它;每一部分都应该是一个单一的、有明确意图的单元。

Why This New Power Matters

为什么这种新能力很重要

Adopting this habit transformed how I work. Code reviews now focus on logic and edge cases rather than deciphering what a variable meant. Onboarding new teammates feels less like handing them a cryptic map and more like giving them a clear guidebook. Most importantly, it reduces the mental tax of “comment drift.” When the code speaks for itself, you spend less time fixing mismatched documentation and more time building features. It’s like upgrading from a flickering torch to a steady lantern—you can see the path ahead, and you’re less likely to trip over hidden roots. 养成这种习惯改变了我的工作方式。现在的代码审查专注于逻辑和边界情况,而不是去破译变量的含义。让新队友入职不再像给他们一张晦涩的地图,而更像是给他们一本清晰的指南。最重要的是,它减少了“注释漂移”带来的心理负担。当代码能自我表达时,你花在修复不匹配文档上的时间就少了,花在构建功能上的时间就多了。这就像从摇曳的火把升级为稳定的灯笼——你能看清前方的道路,也不太容易被隐藏的树根绊倒。

Your Turn

轮到你了

Try this on a small piece of code you’ve written recently. Pick a function or block that currently leans on comments, rename the variables and functions to express intent, and extract any tangled logic into helpers. Notice how the need for comments fades away. 在你最近写的一小段代码上试试这个。挑选一个目前依赖注释的函数或代码块,重命名变量和函数以表达意图,并将纠缠在一起的逻辑提取为辅助函数。你会发现对注释的需求正在逐渐消失。

Challenge: Refactor one messy function today and share the before/after with a teammate. Ask them: “Did you need any comments to understand what it does?” I bet they’ll say no—and you’ll feel that same rush of triumph I felt when I finally escaped that dungeon, lantern in hand. Happy coding, and may your code always speak clearly! 🚀 挑战:今天重构一个混乱的函数,并与队友分享修改前后的对比。问他们:“你需要注释才能理解它的功能吗?”我敢打赌他们会说不需要——那时你就会感受到我当初手持灯笼逃出地牢时那种胜利的快感。祝编码愉快,愿你的代码永远清晰易懂!🚀