Upgrade to Pro — share decks privately, control downloads, hide ads and more …

The 4 Horsemen of Bad Rust Code

Matthias Endler
February 05, 2024
780

The 4 Horsemen of Bad Rust Code

In the right hands, Rust is an exceptionally powerful language. Yet, I frequently observe similar mistakes in Rust programming: treating it like C or Java and not fully utilizing its unique features.

I've concluded that poor Rust coding often falls into a few distinct categories, which I've termed the '4 Horsemen of Bad Rust Code': Overengineering, Simplistic Design, Premature Optimization, and Neglect of Documentation and Testing.

This talk will delve into these antipatterns and offer strategies to avoid them, aiming to share practical tips for writing more ergonomic and effective Rust code. During the talk, we will gradually refactor a Rust code example, transforming it from a less optimal version to a more idiomatic and efficient one.

Matthias Endler

February 05, 2024
Tweet

Transcript

  1. About me • Living in Düsseldorf, Germany • Backend engineer,

    open source maintainer, consultant at corrode.dev • Using Rust since 2015 • "Hello Rust" YouTube and "Rust in Production" Podcast
  2. Ignorance • Uses "stringy-typed" APIs • Mutates liberally • Bad

    or no error handling • Lack of architecture • Prototype-style code
  3. Ignorance: Red Flags • Imperative code • Magic return values

    (-1, "") instead of errors • Everything is a string • u nwr a p() • "c l on e () all the things!" • "mut"
  4. Rusty Rooms Residences;Brussels;2023-04-12;Deluxe;132.19 Ferris Motel One;Athens;2024-10-09;Family;227.43 Cargo Cabin;Oslo;2023-01-24;Double;170.17 Lifetime Lodge;Istanbul;2024-10-15;Family;177.94

    Mutable Manor;Budapest;2023-03-26;Executive;197.24 Ownership Oasis;Prague;2024-11-07;Suite;77.94 Pattern Palace;Madrid;2023-03-17;Executive;195.5 Trait Towers;Amsterdam;2024-05-06;Double;141.94 Async Apartments;Rome;2023-06-28;Single;84.36 Binary Bungalows;Dublin;2024-05-01;Executive;146.57 Crates Cottage;Athens;2023-03-05;Suite;248.67 Data Den;Paris;2023-11-19;Single;238.3 Enum Estate;Berlin;2024-06-12;Double;277.98 Function Flat;Paris;2023-03-05;Double;277.88
  5. Hotel Price in Brussels • Minimum: 40.13 • Mean: 80.42

    • Maximum: 150.20 Expected Result:
  6. CSV is tricky... • Properly handling delimiters is hard. •

    h e l l o;r u st; f os d e m vs "h e l l o;r u st"; f os d e m • Encodings • Headlines? / No headlines? • etc. • Watch "Stop Using CSV"
  7. Fighting Ignorance • Embrace Rust's type system • Lean into

    ownership and borrowing • Learn design patterns • Learn different programming paradigms
  8. Excessive Abstraction: Red Flags • "FileBuilder<T: AsRef<&str>, 'a>" • "I

    might use this again. Let's make it generic!" • "Traits! Traits everywhere!"
  9. FN READ<'A>(&MUT SELF, READ: &'A MUT DYN READ) -> BOX<DYN

    ITERATOR<ITEM = RESULT<HOTEL>> + 'A>;
  10. Fighting Excessive Abstraction • Keep it simple • Avoid unnecessary

    complexity • Watch newcomers use your code • Ensure that abstractions add value
  11. Premature Optimization • Optimizing code before it's necessary • Using

    complex data- structures where simple ones would suffice • Neglecting benchmarks
  12. Premature Optimization: Red Flags • "Without a lifetime, this needs

    to be cloned!" • "Let me help the compiler here." • "Ooof, Box is so much overhead!" • "I use BTreeMap because it's faster than HashMap." • "No need to measure if you've got years of experience." • "Zero-copy abstraction" • "Alocaaaaations!!!"
  13. Find actual performance improvements • Measure! • Profile! •s u

    d o c a r g o f l a m e g r a ph --r e l e a s e • Benchmark! • criterion • divan
  14. Fighting Premature Optimization • Measure, don't guess. • Focus on

    algorithms and data structures, not micro- optimizations • You can get carried away quickly. Be more pragmatic. • Focus on readability and maintainability • Use profiling tools to make informed decisions
  15. Omission • Insufficient Testing • Lack of Documentation • Exposing

    too large APIs • Lack of modularity and encapsulation
  16. Omission: Red Flags • "It compiles. My work is done

    here." • "The code is the documentation." • "Let's just make it all pub." • "I'll refactor that later."
  17. Fighting Omission • Write more documentation • Write unit tests

    for your code • Use tools like clippy, cargo udeps, etc. • Set up CI/CD • Create releases • Keep a changelog
  18. Further reading • RustFest Kiev 2017: Pascal Hertleif - Writing

    Idiomatic Libraries in Rust • FOSDEM 2018: Matthias Endler - Idiomatic Rust • EuroRust 2023: Nikolai Vazquez - Publishing High-Quality Crates
  19. Thanks Illustr a tions by R a chel R a

    c a nelli a nd DALL·E 3