Hasty Briefsbeta

Bilingual

The Compiler Is Your Best Friend, Stop Lying to It

4 months ago
  • #type-safety
  • #programming
  • #compiler
  • The article discusses the importance of not lying to the compiler to avoid runtime errors and improve code safety.
  • It explains what a compiler is and its typical pipeline: parsing, typechecking, optimization, and code generation.
  • Different languages have different compiler behaviors: Rust's ahead-of-time compilation, Java's JIT compilation, and TypeScript's transpilation.
  • Common lies to the compiler include using null, unchecked exceptions, casts, and side-effects, which can lead to runtime errors.
  • The article suggests stopping these lies by using Option types for null, Result types for exceptions, avoiding casts, and separating pure functions from side-effects.
  • By being truthful to the compiler, it can help enforce invariants, making illegal states unrepresentable and improving code safety.
  • Using typed wrappers and union types can help the compiler track more information, making refactoring and understanding code easier.
  • The article concludes with a real-world example of how lying to the compiler (using null) led to a major outage, and how being truthful could have prevented it.