Hacker News 中文摘要

RSS订阅

约翰·卡马克谈可变变量 -- John Carmack on mutable variables

文章摘要

John Carmack反思自己在Python编程中过于依赖"单一赋值"的习惯,建议应避免在循环外的迭代计算中重新赋值或更新变量,保留所有中间计算结果有助于调试。

文章总结

约翰·卡马克谈编程规范:慎用变量重新赋值

著名程序员约翰·卡马克在社交平台分享了他的编程实践心得: 1. 他坦言自己在使用Python时曾对"单一赋值"原则有所松懈,现在需要自我提醒 2. 核心建议:除非是循环中的迭代计算,否则应避免对变量进行重新赋值或更新 3. 保留所有中间计算结果的三大优势: - 便于调试时查看 - 避免代码块移动时 silently 使用错误变量版本 - 增强代码可维护性

延伸建议: - 在C/C++中推荐将大多数变量声明为const - 认为变量默认应为不可变,可变性应通过关键字显式声明

(原文发布时间:2025年10月29日下午5:55)

评论总结

以下是评论内容的总结:

支持默认不可变的观点

  1. 代码可读性与线程安全

    • 严格不可变性使代码更易读且线程安全(gwbas1c)
      "Immutable objects can be read safely from multiple threads... easier to track down what could change"
    • 函数式编程实践(如纯函数)正成为现代代码的最佳实践(munchler)
      "functional programming is slowly becoming the best practice... yet functional languages are still considered fringe"
  2. 语言设计建议

    • 希望默认不可变,mutable作为关键字(munchler、hyperhello)
      "I wish it was the default, and mutable was a keyword"
    • Rust、F#等新语言已实现此设计(bitwize、loeg)
      "Rust gets this right, but I’m stuck with C++ at work"

反对或质疑的观点

  1. 实际开发限制

    • 不可变性在条件分支或异常处理中可能导致代码冗余(stevage、noduerme)
      "y doesn’t exist after the block... try/catch scoping issues"
    • 完全不可变可能牺牲可读性,局部可变性仍有价值(askmrsinh)
      "It can be fine to use mutable variables within a block... as long as assignments are local"
  2. 语言兼容性问题

    • C/C++因历史兼容性难以改变默认行为(shmerl)
      "Proposing immutable by default in C/C++ doesn’t make sense due to backwards compatibility"
    • mutable在C++中已是关键字(但语义不同)(omnicognate)
      "In C++ mutable is a keyword (but doesn’t have the meaning he wants)"

其他观点

  • 行业趋势变化:Java曾推广不可变性,但Go的流行逆转了这一趋势(ronnier)
    "Immutability was gaining traction... then industry switched to golang"
  • 需平衡目标:重点应是引用透明性而非强制不可变(askmrsinh)
    "The main goal should be achieving referential transparency"
  • 开发者体验:Haskell等语言的不可变性初期可能令人不适,但后期带来启发(y0ned4)
    "Felt like in a straitjacket... then, suddenly, the enlightenment"

中立或补充说明

  • 部分语言(如Dart、Clojure)已采用类似实践(jdthedisciple、slifin)
    "In Dart you make everything final by default"
  • 建议IDE可视化标记变量修改(hyperhello)
    "I wish the IDE would provide a small clue... that it was mutated"