m15-anti-pattern

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Anti-Patterns

反模式

Layer 2: Design Choices
第二层:设计选择

Core Question

核心问题

Is this pattern hiding a design problem?
When reviewing code:
  • Is this solving the symptom or the cause?
  • Is there a more idiomatic approach?
  • Does this fight or flow with Rust?

该模式是否隐藏了设计问题?
在审查代码时:
  • 该写法是解决症状还是根源问题?
  • 是否存在更地道的实现方式?
  • 该写法是与Rust的设计理念相悖还是契合?

Anti-Pattern → Better Pattern

反模式 → 更优方案

Anti-PatternWhy BadBetter
.clone()
everywhere
Hides ownership issuesProper references or ownership
.unwrap()
in production
Runtime panics
?
,
expect
, or handling
Rc
when single owner
Unnecessary overheadSimple ownership
unsafe
for convenience
UB riskFind safe pattern
OOP via
Deref
Misleading APIComposition, traits
Giant match armsUnmaintainableExtract to methods
String
everywhere
Allocation waste
&str
,
Cow<str>
Ignoring
#[must_use]
Lost errorsHandle or
let _ =

反模式问题所在更优方案
滥用
.clone()
掩盖所有权问题使用正确的引用或所有权管理
生产环境中使用
.unwrap()
会导致运行时恐慌使用
?
expect
或错误处理逻辑
单所有权场景下使用
Rc
带来不必要的性能开销使用简单的所有权管理
为图方便使用
unsafe
存在未定义行为风险寻找安全的实现模式
通过
Deref
实现OOP
API具有误导性使用组合、trait
巨型match分支难以维护提取为独立方法
滥用
String
造成内存分配浪费使用
&str
Cow<str>
忽略
#[must_use]
标记
丢失错误信息处理错误或使用
let _ =

Thinking Prompt

思考提示

When seeing suspicious code:
  1. Is this symptom or cause?
    • Clone to avoid borrow? → Ownership design issue
    • Unwrap "because it won't fail"? → Unhandled case
  2. What would idiomatic code look like?
    • References instead of clones
    • Iterators instead of index loops
    • Pattern matching instead of flags
  3. Does this fight Rust?
    • Fighting borrow checker → restructure
    • Excessive unsafe → find safe pattern

看到可疑代码时:
  1. 该写法是解决症状还是根源?
    • 通过clone规避借用问题? → 所有权设计存在问题
    • 认为「不会出错」而使用unwrap? → 存在未处理的场景
  2. 地道的Rust代码应该是什么样的?
    • 使用引用而非clone
    • 使用迭代器而非下标循环
    • 使用模式匹配而非标志位
  3. 该写法是否与Rust的设计理念相悖?
    • 与Borrow Checker对抗 → 重构代码结构
    • 过度使用unsafe → 寻找安全的实现模式

Trace Up ↑

向上追溯 ↑

To design understanding:
"Why does my code have so many clones?"
    ↑ Ask: Is the ownership model correct?
    ↑ Check: m09-domain (data flow design)
    ↑ Check: m01-ownership (reference patterns)
Anti-PatternTrace ToQuestion
Clone everywherem01-ownershipWho should own this data?
Unwrap everywherem06-error-handlingWhat's the error strategy?
Rc everywherem09-domainIs ownership clear?
Fighting lifetimesm09-domainShould data structure change?

指向设计层面的理解:
"Why does my code have so many clones?"
    ↑ Ask: Is the ownership model correct?
    ↑ Check: m09-domain (data flow design)
    ↑ Check: m01-ownership (reference patterns)
反模式追溯至问题
滥用.clone()m01-ownership谁应该拥有该数据的所有权?
滥用.unwrap()m06-error-handling错误处理策略是什么?
滥用Rcm09-domain所有权是否清晰?
与生命周期对抗m09-domain是否需要修改数据结构?

Trace Down ↓

向下落地 ↓

To implementation (Layer 1):
"Replace clone with proper ownership"
    ↓ m01-ownership: Reference patterns
    ↓ m02-resource: Smart pointer if needed

"Replace unwrap with proper handling"
    ↓ m06-error-handling: ? operator
    ↓ m06-error-handling: expect with message

指向实现层面(第一层):
"Replace clone with proper ownership"
    ↓ m01-ownership: Reference patterns
    ↓ m02-resource: Smart pointer if needed

"Replace unwrap with proper handling"
    ↓ m06-error-handling: ? operator
    ↓ m06-error-handling: expect with message

Top 5 Beginner Mistakes

初学者五大常见错误

RankMistakeFix
1Clone to escape borrow checkerUse references
2Unwrap in productionPropagate with
?
3String for everythingUse
&str
4Index loopsUse iterators
5Fighting lifetimesRestructure to own data
排名错误修复方案
1通过clone规避Borrow Checker使用引用
2生产环境中使用unwrap使用
?
传播错误
3所有场景都使用String使用
&str
4下标循环使用迭代器
5与生命周期对抗重构代码以合理管理所有权

Code Smell → Refactoring

代码异味 → 重构方案

SmellIndicatesRefactoring
Many
.clone()
Ownership unclearClarify data flow
Many
.unwrap()
Error handling missingAdd proper handling
Many
pub
fields
Encapsulation brokenPrivate + accessors
Deep nestingComplex logicExtract methods
Long functionsMultiple responsibilitiesSplit
Giant enumsMissing abstractionTrait + types

异味预示问题重构方案
大量使用
.clone()
所有权不清晰明确数据流
大量使用
.unwrap()
缺失错误处理添加完善的错误处理逻辑
大量
pub
字段
封装性被破坏使用私有字段+访问器方法
深层嵌套逻辑过于复杂提取为独立方法
超长函数承担多个职责拆分函数
巨型枚举缺失抽象使用Trait+类型

Common Error Patterns

常见错误模式

ErrorAnti-Pattern CauseFix
E0382 use after moveCloning vs ownershipProper references
Panic in productionUnwrap everywhere?, matching
Slow performanceString for all text&str, Cow
Borrow checker fightsWrong structureRestructure
Memory bloatRc/Arc everywhereSimple ownership

错误反模式诱因修复方案
E0382 use after moveClone与所有权管理不当使用正确的引用
生产环境中出现恐慌滥用unwrap使用
?
、模式匹配
性能缓慢所有文本都使用String使用&str、Cow
与Borrow Checker对抗代码结构不合理重构代码结构
内存膨胀滥用Rc/Arc使用简单的所有权管理

Deprecated → Better

已弃用写法 → 更优方案

DeprecatedBetter
Index-based loops
.iter()
,
.enumerate()
collect::<Vec<_>>()
then iterate
Chain iterators
Manual unsafe cell
Cell
,
RefCell
mem::transmute
for casts
as
or
TryFrom
Custom linked list
Vec
,
VecDeque
lazy_static!
std::sync::OnceLock

已弃用写法更优方案
基于下标的循环
.iter()
.enumerate()
collect::<Vec<_>>()
再迭代
链式调用迭代器
手动实现unsafe cell使用
Cell
RefCell
使用
mem::transmute
进行类型转换
使用
as
TryFrom
自定义链表使用
Vec
VecDeque
lazy_static!
使用
std::sync::OnceLock

Quick Review Checklist

快速审查检查清单

  • No
    .clone()
    without justification
  • No
    .unwrap()
    in library code
  • No
    pub
    fields with invariants
  • No index loops when iterator works
  • No
    String
    where
    &str
    suffices
  • No ignored
    #[must_use]
    warnings
  • No
    unsafe
    without SAFETY comment
  • No giant functions (>50 lines)

  • 无合理理由不得使用
    .clone()
  • 库代码中不得使用
    .unwrap()
  • 不得存在带有不变式的
    pub
    字段
  • 可使用迭代器时不得使用下标循环
  • 可使用
    &str
    时不得使用
    String
  • 不得忽略
    #[must_use]
    警告
  • 使用
    unsafe
    时必须添加SAFETY注释
  • 不得存在超长函数(超过50行)

Related Skills

相关技能

WhenSee
Ownership patternsm01-ownership
Error handlingm06-error-handling
Mental modelsm14-mental-model
Performancem10-performance
场景参考内容
所有权模式m01-ownership
错误处理m06-error-handling
心智模型m14-mental-model
性能优化m10-performance