java-clean-code
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseJava Clean Code
Java整洁代码
Improve Java clarity with minimal behavior change. Preserve public APIs unless user asks otherwise.
在尽可能不改变代码行为的前提下提升Java代码的清晰度。除非用户另有要求,否则保留公共API。
Workflow
工作流程
- Understand existing behavior, tests, and local style before editing.
- Remove accidental complexity before adding abstractions.
- Keep changes small, behavior-preserving, and easy to review.
- Add tests only when refactor risk or missing coverage justifies it.
- 在编辑前先理解现有代码的行为、测试用例以及团队本地编码风格。
- 在添加抽象逻辑前先消除偶发复杂度。
- 保持修改范围小、不改变代码行为且易于评审。
- 仅当重构存在风险或测试覆盖率不足时才添加测试用例。
Principles
核心原则
- KISS: choose straightforward control flow over clever composition.
- YAGNI: remove unused extension points, speculative interfaces, and future-only options.
- DRY: remove meaningful duplication; keep duplication when abstraction would hide important differences.
- Single responsibility: give each class/method one clear reason to change.
- Local consistency beats generic best-practice churn.
- Prefer guard clauses when they reduce nesting and expose the normal path.
- KISS:选择直观的控制流而非复杂的巧妙组合。
- YAGNI:移除未使用的扩展点、推测性接口以及仅为未来需求预留的选项。
- DRY:消除有意义的重复代码;若抽象会掩盖重要差异,则保留重复代码。
- 单一职责:为每个类/方法赋予一个明确的变更理由。
- 本地一致性优于通用最佳实践的频繁变动。
- 当卫语句能减少嵌套并突出正常执行路径时,优先使用。
Checks
检查项
- Names reveal domain meaning and avoid vague terms like ,
data,info, ormanagerwhen a precise name exists.helper - Methods are short enough to scan and avoid mixed abstraction levels.
- Branching is simplified with guard clauses where it improves readability.
- Parameters are limited; related arguments become existing DTO/value types only when that matches project style.
- Boolean flags do not hide multiple behaviors in one method.
- Repeated validation, mapping, or query fragments are extracted only when the abstraction has a clear owner.
- Comments explain intent, constraints, or non-obvious tradeoffs; obvious narration is removed.
- Magic values become named constants when they carry domain meaning.
- Primitive obsession is replaced with domain value types only when validation or behavior repeats.
- Null handling is explicit and consistent with project conventions.
- Exceptions preserve context without swallowing causes.
- Refactors do not alter logs, metrics, transactions, or security behavior unintentionally.
- 命名应体现领域含义,若存在精准名称,避免使用、
data、info或manager等模糊术语。helper - 方法应简短到便于快速浏览,且避免混合不同抽象层级。
- 在提升可读性的场景下,使用卫语句简化分支逻辑。
- 限制参数数量;仅当符合项目风格时,将相关参数整合为现有DTO/值类型。
- 布尔标志不应在一个方法中隐藏多种行为。
- 仅当抽象逻辑有明确归属时,才提取重复的验证、映射或查询片段。
- 注释应解释意图、约束或非显而易见的权衡;移除冗余的叙述性注释。
- 当魔法值具有领域含义时,将其转为命名常量。
- 仅当验证或行为重复出现时,才用领域值类型替代基本类型偏执。
- Null处理应明确且符合项目约定。
- 异常应保留上下文信息,不掩盖异常原因。
- 重构不应无意中改变日志、指标、事务或安全相关行为。
Output
输出要求
When reviewing, separate required fixes from optional readability improvements.
See EXAMPLES.md for Java clean-code examples.
评审时,将必需的修复项与可选的可读性优化项区分开。
查看EXAMPLES.md获取Java整洁代码示例。