童子军守则
让你修改过的代码比接手时更整洁一点。
显示原始英文内容
The Boy Scout Rule
Leave the code better than you found it.
Takeaways
- Don't leave bad things rot in a project. This means take a moment to refactor or fix at least one small thing in the area you're working on. It can include anything from variable names to simplifying logic.
- A cleaner codebase is easier to read, work with, and extend. This improves project maintainability and reduces technical debt.
- When every developer follows this rule, it creates a culture of ownership in the code. Teams collectively feel responsible for code quality.
Overview
The Boy Scout Rule basically means: leave the code better than you found it. In practice, it's not about doing big-bang rewrites or achieving perfection in one go. Instead, it's about constant and incremental improvements.
Whenever a developer encounters a piece of code, whether adding a new feature or hunting down a bug, they take the opportunity to polish something nearby. For example, if there's a confusing function name, you rename it clearly. If you notice some duplicated code, you refactor it into a single helper. If a test case is missing for a critical method, you add it.
These are often small changes that might take only a few extra minutes, but they compound over time.
Examples
You're working on an old module to add a new feature. The code works, but you notice a couple of things: there's a function processData() that has more than 200 lines, and there are some //TODO comments and commented-out code blocks. Following the rule, you split processData() into smaller, better-named functions to improve readability and delete those commented-out sections that are no longer needed.
On a larger scale, Google's engineers often say "If you touch it, you own it". This means that when you modify code, you take ownership of its quality, leading to fixing even minor issues as they arise during unrelated tasks. Over the lifespan of a product, thousands of such small clean-ups occur, preventing major problems.
Origins
The mantra "leave the campsite cleaner than you found it" comes from the Boy Scouts of America and Scouting organizations worldwide.
In the domain of software development, the Boy Scout Rule was popularized by Robert C. Martin (Uncle Bob) in his book "Clean Code: A Handbook of Agile Software Craftsmanship" (2008).
Uncle Bob adapted this simple wisdom to software development, recognizing that large refactoring projects rarely happen but continuous small improvements can transform a codebase over time.
核心含义
不要等待一次声势浩大的重构才改善代码。每次修改功能或修复缺陷时,都可以顺手澄清一个命名、删除一段死代码、补充一个测试或简化一小段逻辑。
这些小改进会持续降低理解成本,让代码库保持可工作的状态,同时避免把所有质量问题都推给未来的“大重写”。
实践例子
修改一个旧模块时,发现函数有两百多行、包含注释掉的代码和模糊命名。可以在同一个变更中拆分函数、删除无效内容并补一个边界测试,而不必扩大成一次全面重构。
来源与边界
它借用了童子军“离开营地时比来时更干净”的习惯,后来被罗伯特·马丁带入软件工程语境。改善必须控制在当前任务可承受的范围内,不能借此无限扩大提交范围。