liveBook · Manning

Antipattern

As explained in Idiomatic Rust

An antipattern is a commonly recognized programming practice that is harmful or ineffective in particular contexts or circumstances.

An antipattern is a programming practice considered harmful in a particular context—or sometimes in nearly every context. The label needs a reason: a choice may be unsafe, inefficient, or hard to maintain, but calling an unfamiliar design an antipattern can also be a matter of taste. Treat warnings as prompts to examine tradeoffs, not as rules without exceptions. section 10.0 section 10.1

In Rust, useful warning signs include:

  • Using `unsafe` to bypass the borrow checker. Scrutinize `unsafe` code, even though its use is sometimes necessary. section 10.10
  • Calling `unwrap()` without considering `None` or `Err`. The problem is often neglected error handling, not the method in every possible use. section 10.3
  • Cloning unnecessarily, using `Deref` to emulate polymorphism, or choosing a smart pointer as an escape hatch from the borrow checker. section 10.10
  • Introducing global data or a singleton without weighing tight coupling, testability, and ease of reasoning. section 10.10

Reconsidering `unwrap()`

Before calling `value.unwrap()`, decide what failure should mean. Use `unwrap_or()` for a default, `map()` to transform a present value, `and_then()` to chain fallible operations, or `?` to propagate an error. If the program should exit when an expected value is missing, `expect()` supplies a useful message. It is not a general substitute for handling production errors. section 10.3

Choosing a familiar pattern is not automatically better than departing from it. Ask what problem the practice causes here, whether an alternative makes the code easier to reason about, and whether the circumstances justify an exception. section 10.0 section 1.2

How Idiomatic Rust covers it

How deep it goes
Defines the term and surveys common misuses with alternatives, while treating rules as contextual rather than absolute.
Examples
Uses `unwrap()`, `unsafe`, excessive `clone()`, `Deref`-based polymorphism, globals, and smart-pointer misuse as cases.
What it assumes
Assumes familiarity with Rust constructs such as `Option`, `Result`, and the borrow checker; defines antipattern from the ground up.
What you can do after
Evaluate/understand when a Rust practice warrants an alternative and when its context justifies an exception.
How it connects
Connects antipatterns to design patterns, error handling, the borrow checker, traits, generics, smart pointers, and global data.

Also explained in

Compare how 5 books explain antipattern →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.