Better vs worse
Each entry shows one small task, written two or three ways. The “Worse” version is code that an AI agent could produce: it compiles, it passes a simple test, and it looks reasonable. The “OK” version is acceptable. The “Better” version is what a reviewer would ask for.
Every version is real code in the examples/better-vs-worse crate. Its tests show how the versions differ, for example a test that proves the “Worse” version panics.
How to read an entry
Section titled “How to read an entry”Each entry has:
- The task, in one sentence.
- The versions, labeled Worse, OK, and Better.
- A verdict table. Each version is compared with the Worse version for correctness, failure behavior, performance, readability, and API ergonomics. The scale is Better, Same, or Worse.
- Trade-offs: when the “Worse” version is acceptable. There is almost always a case.
- Related smells and concepts.
Entries
Section titled “Entries”- Read a config fileRead a config file and parse it:
unwrapvs?with context vs a typed error. - Find a user by IDFind a user by ID in a list: a panic and a copy vs
OptionvsOption<&User>. - Count wordsCount words in a text:
contains_keyandinsertvs theHashMapentry API. - Process a list of ordersTurn orders into invoices:
clonevs borrow vsinto_iter. - Model a payment stateA string status vs
boolflags vs anenum. - A shape hierarchyAn abstract-class translation vs trait objects vs an enum.
- Build a request with optional fields
newwith eight parameters vs a builder vsDefaultwith struct update. - Share a cache between threads
Arc<Mutex<HashMap>>vsRwLockvs a concurrent map vs message passing.Not written yet. - Fetch three URLsSequential
awaitvsjoin!vs a blocking client in async code.Not written yet. - Parse numbers from input
ascasts vstry_fromvsparsewith typed errors. - A linked or tree structure
Rc<RefCell>vsBoxvs an arena with indices. - Return a collection
Vecvsimpl Iteratorvs a slice. - Read a large fileRead all into a
StringvsBufReader::lines. - Error types for a library
StringvsBox<dyn Error>vs athiserrorenum.