Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Stringly-Typed Code

Smell. String doing the job of a type: states ("connected"), identifiers, values with units in suffixes ("250ms"), enums by convention (kind: String), and HashMap<String, String> as a data model. Related: functions taking several bools, and bare f64s whose unit lives in a comment.

Why generation produces it. Strings are the shortest path from a prose spec to code. If the spec says “the status can be connected or idle”, a String transcribes that sentence directly. Defining an enum requires interpreting it.

Principle. Closed sets are enums, validated values are newtypes, and quantities carry units. Every string comparison is a place where a typo compiles, and every stringly parameter is an invariant the compiler was never told about.

Prompt. “Replace stringly-typed values: model status as an enum, wrap device_id in a newtype with a fallible constructor, and use std::time::Duration for durations. Keep strings only for freeform text.”