← 返回规律列表
质量

墨菲定律

凡是可能出错的事情,最终都有可能出错。

显示原始英文内容

Murphy's Law / Sod's Law

Anything that can go wrong will go wrong.

Takeaways

  • If an error can happen, it will happen. Plan and code defensively with this in mind.
  • Add error handling, backups, and checks.
  • Edge cases will occur in production. Write tests for these kinds of scenarios.

Overview

In software, Murphy's Law is often used to explain bugs and production incidents: whatever can go wrong in code (a null pointer, a race condition, a network outage) eventually will manifest, especially in large user bases or at the worst possible time.

In practice, this law encourages developers to write more defensive code. This means checking for nulls, handling exceptions, validating inputs, and failing gracefully when errors occur. It also reminds DevOps teams to anticipate failures by implementing monitoring, enabling rollbacks, and maintaining contingency plans.

Examples

If a web form field can accept text, someone will enter a 10,000-character string of weird symbols to see what happens, unless you've explicitly handled it. If memory can run out, it will be when multiple processes align just so.

A famous real-world instance was during a live demo (who remembers the Windows 98 presentation by Bill Gates?), if something can glitch, it likely will.

In coding, consider a function that assumes an input file exists. Murphy's Law says that one day that file won't be there or will be corrupted, so your code should handle the file-not-found or bad-data scenario rather than crash.

Another typical case is that the server will crash on your only day off, because that's when it's most likely to cause trouble. Engineers thus build highly available systems and pager rotations to mitigate Murphy's Law.

Origins

Attributed to Edward A. Murphy Jr., an engineer working on rocket sled experiments in 1949. It became popular in aerospace and then everywhere. In software, it's been around as long as bugs have, constantly reminding us that if there's one untested scenario, one user will find it.

核心含义

系统中的边界情况、异常路径和人为失误不会因为没有被测试就消失。真正重要的不是悲观预测一切,而是主动寻找失败方式,让失败变得可观测、可恢复且影响受控。

可靠性工程把这条经验转化为故障注入、混沌演练、限流、熔断、备份和灾难恢复。

实践例子

部署恰好发生在证书过期、磁盘将满或第三方服务超时的时刻。若系统只有成功路径,偶然事件就会变成大面积故障;若有告警、回滚和降级,影响可以被限制。

来源与边界

墨菲定律有多种版本和来源。它不是“所有事情都会失败”,而是提醒我们不要把偶然成功误认为系统具备了可靠性。