From 9c1d7d1f292ec1d20aa493b7b7fd07dcc7261017 Mon Sep 17 00:00:00 2001 From: tall-vase Date: Fri, 5 Dec 2025 13:25:31 +0000 Subject: [PATCH 1/4] Bring in existing foundations of API design work from google doc --- src/SUMMARY.md | 33 +++++++++ src/idiomatic/foundations-api-design.md | 3 + .../clarity-readability.md | 0 .../meaningful-doc-comments.md | 23 ++++++ .../avoid-redundancy.md | 55 ++++++++++++++ .../name-drop-signpost.md | 55 ++++++++++++++ .../meaningful-doc-comments/what-isnt-docs.md | 22 ++++++ .../what-why-not-how-where.md | 46 ++++++++++++ .../who-are-you-writing-for.md | 34 +++++++++ .../foundations-api-design/predictable-api.md | 10 +++ .../predictable-api/common-traits.md | 30 ++++++++ .../predictable-api/common-traits/01-debug.md | 74 +++++++++++++++++++ .../common-traits/02-partialeq-eq.md | 53 +++++++++++++ .../common-traits/03-partialord-ord.md | 64 ++++++++++++++++ .../predictable-api/common-traits/04-hash.md | 36 +++++++++ .../predictable-api/common-traits/05-clone.md | 48 ++++++++++++ .../predictable-api/common-traits/06-copy.md | 47 ++++++++++++ .../predictable-api/common-traits/07-serde.md | 36 +++++++++ .../common-traits/08-from-into.md | 58 +++++++++++++++ .../common-traits/09-try-from-into.md | 45 +++++++++++ .../common-traits/10-display.md | 46 ++++++++++++ .../predictable-api/naming-conventions.md | 20 +++++ .../naming-conventions/01-get.md | 31 ++++++++ .../naming-conventions/02-push.md | 29 ++++++++ .../naming-conventions/03-is.md | 27 +++++++ .../naming-conventions/04-mut.md | 24 ++++++ .../naming-conventions/05-try.md | 27 +++++++ .../naming-conventions/06-with.md | 31 ++++++++ .../naming-conventions/07-from.md | 25 +++++++ .../naming-conventions/08-into.md | 29 ++++++++ .../naming-conventions/09-owned.md | 21 ++++++ .../naming-conventions/10-by.md | 25 +++++++ .../naming-conventions/11-unchecked.md | 25 +++++++ .../naming-conventions/12-to.md | 29 ++++++++ .../naming-conventions/13-as-and-ref.md | 38 ++++++++++ .../naming-conventions/14-mini-exercise.md | 32 ++++++++ 36 files changed, 1231 insertions(+) create mode 100644 src/idiomatic/foundations-api-design.md create mode 100644 src/idiomatic/foundations-api-design/clarity-readability.md create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments.md create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/01-debug.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/02-partialeq-eq.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/03-partialord-ord.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/04-hash.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/06-copy.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/07-serde.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/08-from-into.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/09-try-from-into.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/common-traits/10-display.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index a5929bad8455..d9f89f076291 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -436,6 +436,39 @@ # Idiomatic Rust - [Welcome](idiomatic/welcome.md) +- [Foundations of API Design](idiomatic/foundations-api-design.md) + - [Meaningful Doc Comments](idiomatic/foundations-api-design/meaningful-doc-comments.md) + - [Avoid Redundancy](idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md) + - [Name Drop and Signpost](idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md) + - [Name and Signature are Not Enough](idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md) + - [What and Why, not How and Where](idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md) + - [Who Are You Writing For?](idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md) + - [Predictable API](idiomatic/foundations-api-design/predictable-api.md) + - [Naming conventions](idiomatic/foundations-api-design/predictable-api/naming-conventions.md) + - [Get](idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md) + - [Push](idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md) + - [Is](idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md) + - [Mut](idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md) + - [Try](idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md) + - [With](idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md) + - [From](idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md) + - [Into](idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md) + - [Owned](idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md) + - [By](idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md) + - [To](idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md) + - [As and Ref](idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md) + - [Mini Exercise](idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md) + - [Implementing Common Traits](idiomatic/foundations-api-design/predictable-api/common-traits.md) + - [Debug](idiomatic/foundations-api-design/predictable-api/common-traits/01-debug.md) + - [PartialEq and Eq](idiomatic/foundations-api-design/predictable-api/common-traits/02-partialeq-eq.md) + - [PartialOrd and Ord](idiomatic/foundations-api-design/predictable-api/common-traits/03-partialord-ord.md) + - [Hash](idiomatic/foundations-api-design/predictable-api/common-traits/04-hash.md) + - [Clone](idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md) + - [Copy](idiomatic/foundations-api-design/predictable-api/common-traits/06-copy.md) + - [Serialize and Deserialize](idiomatic/foundations-api-design/predictable-api/common-traits/07-serde.md) + - [From and Into](idiomatic/foundations-api-design/predictable-api/common-traits/08-from-into.md) + - [TryFrom and TryInto](idiomatic/foundations-api-design/predictable-api/common-traits/09-try-from-into.md) + - [Display](idiomatic/foundations-api-design/predictable-api/common-traits/10-display.md) - [Leveraging the Type System](idiomatic/leveraging-the-type-system.md) - [Newtype Pattern](idiomatic/leveraging-the-type-system/newtype-pattern.md) - [Semantic Confusion](idiomatic/leveraging-the-type-system/newtype-pattern/semantic-confusion.md) diff --git a/src/idiomatic/foundations-api-design.md b/src/idiomatic/foundations-api-design.md new file mode 100644 index 000000000000..ab32b5a95bae --- /dev/null +++ b/src/idiomatic/foundations-api-design.md @@ -0,0 +1,3 @@ +--- +minutes: 2 +--- diff --git a/src/idiomatic/foundations-api-design/clarity-readability.md b/src/idiomatic/foundations-api-design/clarity-readability.md new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments.md new file mode 100644 index 000000000000..de7fb8c72eec --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments.md @@ -0,0 +1,23 @@ +--- +minutes: 5 +--- + +# Meaningful Doc Comments + +```rust,compile_fail +/// API for Domain // ❌ +pub mod domain {} + +/// Function from A to B // ❌ +fn a_to_b(a: A) -> B {...} + +/// Does X // ❌ +fn do_x() {} +``` + +Doc comments are the most common source of documentation most developers will +engage with. + +It's important to write doc comments that developers will appreciate reading, +that gives them the information they are looking for and doesn't just re-state +the obvious. diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md new file mode 100644 index 000000000000..9127495e9709 --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md @@ -0,0 +1,55 @@ +--- +minutes: 15 +--- + +# Avoiding Redundancy + +Function names and type signatures already document some information, avoid +repeating them! + +```rust +// Don't do this! +/// Parses an ipv4 from a str. Returns an option for failure modes. +fn parse_ip_addr_v4(input: &str) -> Option { ... } + +// TODO: couple more of these, for the instructor to go through with students. +``` + +
+- Motivation: Documentation that repeats name/signature information provides nothing new to the API user. + +- This is an understandable pattern to fall into! + + Naive approach to "always document your code," follows this advice literally + but does not follow the intent. + + Tests might enforce documentation coverage, this kind of documentation is an + easy fix. + +- The name of a function or type is part of the documentation of that function + or type. + + Similarly, the signature of a function is part of the documentation of that + function. + + Therefore: aspects of the subject are already covered when you start writing + doc comments! + +- Many areas of the standard library have minimal documentation because the name + and types do give enough information. + + Rule of Thumb: What information is missing from a user's perspective? Other + than name, signature, and irrelevant details of the implementation. + +- Don't drop down to language basics! Assume the reader of doc comments has an + intermediate understanding of the language itself, it's the API you're working + on that you're trying to document. + +- If there is a complex topic involved with the functions and types you're + documenting, signpost to a "source of truth" if one exists such as a blog + post, an internal document, a paper etc. + +- Collaborate with Students: Go through the methods in the slide and discuss + what might be relevant to an API user. + +
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md new file mode 100644 index 000000000000..be513a295f88 --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md @@ -0,0 +1,55 @@ +--- +minutes: 15 +--- + +# Name-dropping keywords and signposting topics + +```rust +/// This function covers , for further reading see: reference A, B, C. +fn highly_specific_function(/* */) { /* ... */ +} +``` + +
+- Motivation: Readers of documentation will not be closely reading most of your doc comments like they would dialogue in a novel they love. + +Users will most likely be skimming and scan-reading to find the part of the +documentation that is relevant to whatever problem they're trying to solve in +the moment. + +Once a user has found a keyword or potential signpost that's relevant to them +they will begin to search for context surrounding what is being documented. + +- Ask the class: What do you look for in documentation? Focus on the + moment-to-moment searching for information here, not general values in + documentation + +- Name-drop keywords close to the beginning of a paragraph. + + This aids skimming and scanning, as the first few words of a paragraph stand + out the most. + + Skimming and scanning lets users quickly navigate a text, keeping keywords as + close to the beginning of a paragraph as possible lets a user + +- Signpost, but don't over-explain. + + Users will not necessarily have the same domain expertise as an API designer. + + If a tangential, specialist term or acronym is mentioned try to bring in + enough context such that a novice could quickly do more research. + +- Signposting often happens organically, consider a networking library that + mentions various protocols. But when it doesn't happen organically, it can be + difficult to choose what to mention. + + Rule of thumb: API developers should be asking themselves "if a novice ran + into what they are documenting, what sources would they look up and are there + any red herrings they might end up following"? + + Users should be given enough information to look up subjects on their own. + +- What we've already covered, predictability of an API including the naming + conventions, is a form of signposting. + +
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md new file mode 100644 index 000000000000..e67b4d453485 --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md @@ -0,0 +1,22 @@ +--- +minutes: 5 +--- + +Names and Signatures are not full documentation + +```rust +``` + +
+- Motivation: API designers can over-commit to the idea that a function name and signature is enough documentation. + +It's better than nothing, but it's worse than good documentation. + +- Again, names and types are _part_ of the documentation. They are not always + the full story! + +- TODO: give some rules of thumb for when to go into more detail, + cross-reference rust stdlib docs. This may live better in the name conventions + area. + +
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md new file mode 100644 index 000000000000..9eeb41f7f7d1 --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md @@ -0,0 +1,46 @@ +--- +minutes: 10 +--- + +# Why and What, not How and Where + +Avoid documenting irrelevant details that may frequently change. + +```rust,no_compile +/// Sorts a slice. Implemented using recursive quicksort. +fn sort_quickly(to_sort: &mut [T]) { /* ... */ +} + +/// Calls an org-internal service using reqwest. +fn ask_service(url: &str) -> String { /* ... */ +} +``` + +
+- Motivation: Using doc comments to explain how a function does something internally means if that internal implementation detail changes, the doc comment needs to change as well. + +Internal information is likely irrelevant to a user. Imagine explaining in a doc +comment for a function that you're using for loops to solve a problem, what is +the point of this information? + +- It could be that the implementation is necessary to explain, but this is + likely due to whatever effects or invariants the user of that API needs to be + aware of instead. + + Focus on those effects and invariants instead of instead of the implementation + details themselves. + + Reiterate: Implementation details can and will change, so do not explain these + details. + + TODO: Real-life example of something appropriate to a large system. + +- Don't talk about where something is used for the sake of it. + + This is another instance where this information can become stale quickly. + +- Prefer instead to focus on what the function does (though again, not how it is + implemented) for a user trying to reach this practical information as quickly + as possible. + +
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md new file mode 100644 index 000000000000..6f7545283c3e --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md @@ -0,0 +1,34 @@ +--- +minutes: 10 +--- + +# Who are you writing for? + +Colleagues, collaborators, largely-silent API users, or just yourself? + +```rust +// TODO: What's a good illustration here? +``` + +
+- Motivation: It can be easy to fall into a pattern of writing only for you, but most documentation is for people coming in with a different perspective. + +- Unintentionally writing for yourself can lead to people not understanding a + point you're trying to make or the concept you're trying to articulate. + +- Imagine a version of you, or others you've known, struggling to find practical + information while going through documentation. + + Keep this idea of a person in mind when thinking about what areas of a + codebase need attention for doc comments. + +- Who are you writing for? + +- Also imagine a version of you, or others you've known, who is struggling to + find the important details in winding, extensive doc comments. Don't give too + much information. +- Always ask: Is this documentation making it difficult for the API user? Are + they able to quickly grasp what they need or find out where they could need + it? + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api.md b/src/idiomatic/foundations-api-design/predictable-api.md new file mode 100644 index 000000000000..a1dc020edd8a --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api.md @@ -0,0 +1,10 @@ +--- +minutes: 2 +--- + +# Predictable API + +Keep your APIs predictable through naming conventions and implementing common +traits. + + diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits.md new file mode 100644 index 000000000000..9c25c382f465 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits.md @@ -0,0 +1,30 @@ +--- +minutes: 5 +--- + +# Common Traits to Implement + +```rust +#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone /* ... */)] +pub struct MyData { + pub name: String, + pub number: usize, + pub data: [u8; 64], +} +``` + +
+- Traits are one of the most potent tools in the Rust language. The language and ecosystem expects you to use them, and so a big part of _predictability_ is what traits are implemented for a type! + +- Traits should be liberally implemented on types you author, but there are + caveats! + +- Remember, many traits have the ability to be _derived_: to have a compiler + plugin (macro) write the implementation for you! + +- Authors of ecosystem traits (like De/Serialize) have made derive + implementations for traits available to users, leading to very little + commitment needed on the developer side for implementing these kinds of + traits! + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/01-debug.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/01-debug.md new file mode 100644 index 000000000000..83dbca2482df --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/01-debug.md @@ -0,0 +1,74 @@ +--- +minutes: 5 +--- + +# Debug + +"Write to string" trait, for debug purposes. + +Derivable: ✅ When to implement: Almost always + +```rust +// pub trait Debug { +// fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>; +// } + +#[derive(Debug)] +pub struct Date { + day: u8, + month: u8, + year: i64, +} + +#[derive(Debug)] +pub struct User { + name: String, + date_of_birth: Date, +} + +pub struct PlainTextPassword { + password: String, + hint: String, +} + +impl std::fmt::Debug for PlainTextPassword { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PlainTextPassword") + .field("hint", &self.hint) + .field("password", &"[omitted]") + .finish() + } +} + +fn main() { + let user = User { + name: "Alice".to_string(), + date_of_birth: Date { day: 31, month: 10, year: 2002 }, + }; + + println!("{user:?}"); + println!( + "{:?}", + PlainTextPassword { + password: "Password123".to_string(), + hint: "Used it for years".to_string() + } + ); +} +``` + +
+- Provides trivial "write to string" functionality. + +- Formatting for _debug information_ for programmers during , not appearance or + serialization. + +- Allows for use of `{:?}` and `{#?}` interpolation in string formatting macros. + +- When to not derive/implement: If a struct holds sensitive data, investigate if + you should implement Debug for it. + + If Debug is needed, consider manually implementing Debug rather than deriving + it. Omit the sensitive data from the implementation. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/02-partialeq-eq.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/02-partialeq-eq.md new file mode 100644 index 000000000000..1336c8453c96 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/02-partialeq-eq.md @@ -0,0 +1,53 @@ +--- +minutes: 10 +--- + +PartialEq and Eq + +Partial equality & Total equality. + +Derivable: ✅ When to implement: Almost always. + +```rust +// pub trait PartialEq +//{ +// // Required method +// fn eq(&self, other: &Rhs) -> bool; +// +// // Provided method +// fn ne(&self, other: &Rhs) -> bool { ... } +// } +// +// pub trait Eq: PartialEq { } + +#[derive(PartialEq, Eq)] +pub struct User { name: String, favorite_number: i32 } + +let alice = User { name: "alice".to_string(), favorite_number: 1_000_042 }; +let bob = User { name: "bob".to_string(), favorite_number: 42 }; + +dbg!(alice == alice); +dbg!(alice == bob); +``` + +
+- Equality-related methods. If a type implements `PartialEq`/`Eq` then you can use the `==` operator with that type. + +- A type can't implement `Eq` without implementing `PartialEq`. + +- Reminder: Partial means "there are invalid members of this set for this + function." + + This doesn't mean that equality will panic, or that it returns a result, just + that there may be values that may not behave as you expect equality to behave. + + For example, with floating point values `NaN` is an outlier: `NaN == NaN` is + false, despite bitwise equality. + + `PartialEq` exists to separate types like f32/f64 from types with Total + Equality. + +- You can implement `PartialEq` between different types, but this is mostly + useful for reference/smart pointer types. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/03-partialord-ord.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/03-partialord-ord.md new file mode 100644 index 000000000000..b55f856738f8 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/03-partialord-ord.md @@ -0,0 +1,64 @@ +--- +minutes: 10 +--- + +# PartialOrd and Ord + +Partial ordering & Total ordering. + +Derivable: ✅ When to implement: Almost always. + +```rust +// pub trait PartialOrd: PartialEq +// { +// // Required method +// fn partial_cmp(&self, other: &Rhs) -> Option; +// +// /* Provided methods omitted */ +// } +// pub trait Ord: Eq + PartialOrd { +// // Required method +// fn cmp(&self, other: &Self) -> Ordering; +// +// /* Provided methods omitted */ +// } + +#[derive(PartialEq, PartialOrd)] +pub struct Partially(f32); + +#[derive(PartialEq, Eq, PartialOrd, Ord)] +pub struct Totally { + id: u32, + name: String, +} +``` + +
+- Comparison-related methods. If a type implements `PartialOrd`/`Ord` then you can use comparison operators (`<`, `<=`, `>`, `>=`) with that type. + +`Ord` gives access to `min`, `max`, and `clamp` methods. + +- When derived, compares things in the order they are defined. + + For enums this means each variant is considered "greater than" the last as + they are written. + + For structs this means fields are compared as they are written, so `id` fields + are compared before `name` fields in `Totally`. + +- Prerequisites: `PartialEq` for `PartialOrd`, `Eq` for `Ord`. + + To implement `Ord`, a type must also implement `PartialEq`, `Eq`, and + `PartialOrd`. + +- Like with `PartialEq` and `Eq`, a type cannot implement `Ord` without + implementing `PartialOrd`. + + Like those equality traits, `PartialOrd` exists to separate types with + non-total ordering (particularly floating-point numbers) from types with total + ordering. + +- Used for sorting/searching algorithms and maintaining the ordering of + `BTreeMap`/`BTreeSet` style data types. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/04-hash.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/04-hash.md new file mode 100644 index 000000000000..eff5d40c3432 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/04-hash.md @@ -0,0 +1,36 @@ +--- +minutes: 2 +--- + +# Hash + +Performing a hash on a type. + +Derivable: ✅ When to implement: Almost always. + +```rust +// pub trait Hash { +// // Required method +// fn hash(&self, state: &mut H) +// where H: Hasher; +// +// // Provided method +// fn hash_slice(data: &[Self], state: &mut H) +// where H: Hasher, +// Self: Sized { ... } +// } + +#[derive(Hash)] +pub struct User { + id: u32, + name: String, + friends: Vec, +} +``` + +
+- Allows a type to be used in hash algorithms. + +- Most commonly used with data structures like `HashMap`. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md new file mode 100644 index 000000000000..67070b21dd7c --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md @@ -0,0 +1,48 @@ +--- +minutes: 5 +--- + +# Clone + +Deep-copy a type or duplicate a smart, shareable pointer. + +Derivable: ✅ When to implement: If duplicating doesn't break invariants. + +```rust +// pub trait Clone: Sized { +// // Required method +// fn clone(&self) -> Self; +// +// // Provided methods omitted +// } + +use std::collections::BTreeMap; +use std::rc::Rc; + +#[derive(Clone)] +pub struct LotsOfData { + string: String, + vec: Vec, + set: BTreeSet, +} + +let lots_of_data = LotsOfData { + string: "String".to_string(), + vec: vec![1; 255], + set: [1, 2, 3, 4, 5, 6, 7, 8].iter().collect(), +} + +let lod_cloned = lots_of_data.clone(); + +let reference_counted = Rc::new(lots_of_data); +// Copies the reference-counted pointer, not the value. +let reference_copied = reference_counted.clone(); +``` + +
+- Deep clones a value, or in the case of smart pointers like `Rc`/`Arc` create a new instance of that pointer. + +- When to not implement/derive: For types that, to maintain an invariant, the + value should not be duplicated. We'll touch on this later in Idiomatic Rust. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/06-copy.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/06-copy.md new file mode 100644 index 000000000000..aed0f11ddbc7 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/06-copy.md @@ -0,0 +1,47 @@ +--- +minutes: 10 +--- + +# Copy + +Like `Clone`, but indicates the type is can be bitwise copied. + +Derivable: ✅ When to implement: Sometimes. + +```rust +// Copy is just a marker trait with Clone as a supertrait. +// pub trait Copy: Clone { } + +#[derive(Clone, Copy)] +pub struct Copyable(u8, u16, u32, u64); +``` + +
+- Clone represents a deep clone, and so does copy, but copy suggests to the compiler that a value can be copied bitwise. + +- When not to implement/derive: If you do not want to implicitly create copies + when dereferencing values of a type, do not implement this trait. + + Copy enables implicit duplication, so be careful about what types you're + implementing this on. + +- Ask the class: Can a type with heap data (`Vec`, `BTreeMap`, `Rc`, etc.) be + copy? Should it be? + + It both cannot and should not, this is a misuse of this trait. + + Bitwise copying on these types would mean types with heap data would no longer + have exclusive ownership of a pointer, breaking the invariants usually upheld + by Rust and its ecosystem. + + Multiple `Vec`s would point to the same data in memory. Adding and removing + data would only update individual `Vec`s length and capacity values. The same + for `BTreeMap`. + + Bitwise copying of `Rc`s would not update the reference counting value within + the pointers, meaning there could be two instances of a `Rc` value that + believe themselves to be the only `Rc` for that pointer. Once one of them is + destroyed, the reference count will become 0 on one of them and the inner + value dropped despite there being another `Rc` still alive. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/07-serde.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/07-serde.md new file mode 100644 index 000000000000..c36ec9282375 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/07-serde.md @@ -0,0 +1,36 @@ +--- +minutes: 5 +--- + +Serialize/Deserialize style traits + +Crates like `serde` can implement serialization automatically. + +Derivable: ✅ When to implement: Almost always. + +```rust,no_compile +#[derive(Serialize, Deserialize)] +struct ExtraData { + fav_color: String, + name_of_dog: String, +} + +#[derive(Serialize, Deserialize)] +struct Data { + name: String, + age: usize, + extra_data: ExtraData, +} +``` + +
+- Provides serialization and deserialization functionality for a type. + +- When not to implement: If a type contains sensitive data that should not be + erroneously saved to disk or sent over a network, consider not implementing + Serialize/Deserialize for that type. + + Shares security concerns with `Debug`, but given serialization is often used + in networking there can be higher stakes. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/08-from-into.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/08-from-into.md new file mode 100644 index 000000000000..4bb6cb9ac8cb --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/08-from-into.md @@ -0,0 +1,58 @@ +--- +minutes: 5 +--- + +# From & Into + +Conversion from one type to another. + +Derivable: ❌, without crates like `derive_more`. When to implement: As-needed +and convenient. + +```rust +pub struct ObviousImplementation(String); + +impl From for ObviousImplementation { + fn from(value: String) -> Self { + ObviousImplementation(value) + } +} + +impl From<&str> for ObviousImplementation { + fn from(value: &str) -> Self { + ObviousImplementation(value.to_owned()) + } +} + +fn main() { + // From String + let obvious1 = ObviousImplementation::from("Hello, obvious!".to_string()); + // From &str + let obvious2 = ObviousImplementation::from("Hello, obvious!"); + // A From implementation implies an Into implementation, &str.into() -> + // ObviousImplementation + let obvious3: ObviousImplementation = "Hello, implementation!".into(); +} +``` + +
+- Provides conversion functionality to types. + +- The two traits exist to express different areas you'll find conversion in + codebases. + +- `From` provides a constructor-style function, whereas into provides a method + on an existing value. + +- Prefer writing `From` implementations for a type you're authoring instead + of `Into`. + + The `Into` trait is implemented for any type that implements `From` + automatically. + + `Into` is preferred as a trait bound for arguments to functions for clarity of + intent for what the function can take. + + `T: Into` has clearer intent than `String: From`. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/09-try-from-into.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/09-try-from-into.md new file mode 100644 index 000000000000..fd370bce9698 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/09-try-from-into.md @@ -0,0 +1,45 @@ +--- +minutes: 5 +--- + +# TryFrom/TryInto + +Fallible conversion from one type to another. + +Derivable: ❌ When to implement: As-needed. + +```rust +#[derive(Debug)] +pub struct InvalidNumber; + +#[derive(Debug)] +pub struct DivisibleByTwo(usize); + +impl TryFrom for DivisibleByTwo { + type Error = InvalidNumber; + fn try_from(value: usize) -> Result { + if value.rem_euclid(2) == 0 { + Ok(DivisibleByTwo(value)) + } else { + Err(InvalidNumber) + } + } +} + +fn main() { + let success: Result = 4.try_into(); + dbg!(success); + let fail: Result = 5.try_into(); + dbg!(fail); +} +``` + +
+- Provides conversion that can fail, returning a result type. + +- Like `From`/`Into`, prefer implementing `TryFrom` for types rather than + `TryInto`. + +- Implementations can specify what the error type of the `Result`. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/10-display.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/10-display.md new file mode 100644 index 000000000000..e1eacb3a0cd3 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/10-display.md @@ -0,0 +1,46 @@ +--- +minutes: 5 +--- + +# Display + +"Write to string" trait, prioritizing readability for an end user. + +Derivable: ❌, without crates like `derive_more`. When to implement: As-needed, +for errors and other types that an end-user will see. + +```rust +pub enum NetworkError { + HttpCode(u16), + WhaleBitTheUnderseaCable, +} + +impl std::fmt::Display for NetworkError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match self { + HttpCode(code) => write!(f, "HTTP Error code {code}"), + WhaleBitTheUnderseaCable => { + write!(f, "Whale attack detected – call Ishmael") + } + } + } +} + +impl std::error::Error for NetworkError {} +``` + +
+- A trait similar to `Debug`, but with a focus on end-user readability. + +- Prerequisite for the `Error` trait. + + If implementing for an error type, focus on providing a descriptive error for + users and programmers other than you. + +- Same security considerations as Debug, consider the ways that sensitive data + could be exposed in UI or logs. + +- Types that implement `Display` automatically have `ToString` implemented for + them. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions.md new file mode 100644 index 000000000000..91e306686e3b --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions.md @@ -0,0 +1,20 @@ +--- +minutes: 2 +--- + +# Naming Conventions + +
+- One core component of readability and predictability is the way function names are composed. + +A formal and consistently-applied naming convention lets developers treat names +like a domain-specific language and quickly understand the functionality and use +cases of a method. + +Rust's community developed naming conventions early, making them mostly +consistent in places like the standard library. + +- Here we'll learn common components of rust method names, giving examples from + the standard library and some context to go with them. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md new file mode 100644 index 000000000000..25aac6450d88 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md @@ -0,0 +1,31 @@ +--- +minutes: 2 +--- + +# Get + +Getting an element from a collection or container. + +```rust +// Safe, fallible indexing. +let items: Vec = vec![1, 2, 3]; +let option = items.get(0); // &Vec -> Option<&u8> +assert_eq!(Some(1), option); +let failed_option = items.get(1000); // &Vec -> Option<&u8> +assert_eq!(None, option); +``` + +
+- Gets are trivial, they get a value! + +Immutable by default, for the most part. + +Should not panic. May return an option or result, depending on the framework. + +- Not for fields! + + For private fields you don't want users to have direct, assign-level access t + a method with a more descriptive name (or the same name as the field) is + preferred. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md new file mode 100644 index 000000000000..9edc82e9822c --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md @@ -0,0 +1,29 @@ +--- +minutes: 2 +--- + +# Push + +Common on array-like structures. + +```rust +use std::collections::VecDeque; + +let mut items: Vec = Vec::new(); +items.push(42); +let mut items_queue: VecDeque = VecDeque::new(); +items_queue.push_front(233); +// [233] +items_queue.push_back(42); +// [233, 42] +items_queue.push_front(128); +// [128, 233, 42] +dbg!(items_queue); +``` + +
+- Modifies an array-like structure by adding an element. + +Needs mutable access! + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md new file mode 100644 index 000000000000..f03e3432562b --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md @@ -0,0 +1,27 @@ +--- +minutes: 2 +--- + +# Is + +Check a condition about a datatype. + +```rust +// TODO: Should this just be no-compile versions that +dbg!("".is_empty()); +dbg!(vec![1u32].is_empty()); +dbg!(f32::NAN.is_nan()); +// No is_not_nan method, don't write these kinds of methods! +dbg!(!0.99.is_nan()); +dbg!(64u32.is_power_of_two()); +``` + +
+- A boolean condition on a value. + +`is` prefix is preferred over methods with `not` in the name. + +There are no instances of `is_not_` in standard library methods, just use +`!value.is_`. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md new file mode 100644 index 000000000000..eac0940c1f01 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md @@ -0,0 +1,24 @@ +--- +minutes: 2 +--- + +# Mut + +Suffix for access-style methods. + +```rust +Vec::get_mut +// Iterate over a slice by mutable reference, being able to mutate +// items in the iterator as you iterate over them. +slice::iter_mut +RefCell::get_mut +``` + +
+- Mut for Mutability + +- Suffix that signifies the method gives access to a mutable reference. + + Requires mutable access to the value you're calling this method on. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md new file mode 100644 index 000000000000..12b8b3441343 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md @@ -0,0 +1,27 @@ +--- +minutes: 2 +--- + +# Try + +Prefix for fallible methods that return a `Result`. + +```rust +``` + +
+- Prefix for methods that can fail, returning a `Result`. + +- `TryFrom` is a `From`-like trait for types whose single-value constructors + might fail in some way. + +- Ask: Why aren't `Vec::get` and other similar methods `try_get`? + + There's only one possible error with get-style methods, out-of-bounds or + key-does-not-exist style access errors. + + Also: get-style methods will be used frequently with data types like hash + maps, sets. `get` is shorter and faster to scan visually than try_get, if try + were more prolific. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md new file mode 100644 index 000000000000..89bea4fc556a --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md @@ -0,0 +1,31 @@ +--- +minutes: 5 +--- + +# With + +Prefix for builder-style configuration. + +```rust +{Vec, BTreeSet}::with_capacity +PathBuf::with_extension +PathBuf::with_file_name +``` + +
+- Prefix for methods that set something internally. + +Can be constructors, builders, or setters. + +- Constructor-style `with` methods usually set one specific field but leave + everything else "default" + + `with_capacity` allocates enough space for the number of elements given, but + does not otherwise add anything to the data structure. + +- When `with` methods take an owned value, they're builder-style. + +- When `with` methods take a reference, like pathbuf's `with` methods, they + return a new owned value while the original value remains. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md new file mode 100644 index 000000000000..9bbe0c29825e --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md @@ -0,0 +1,25 @@ +--- +minutes: 2 +--- + +# From + +Prefix for a constructor-style function. + +```rust +// TODO: more examples +Vec::from_raw_parts, from_iter, from_le_bytes +``` + +
+- Prefix for constructor-style, `From`-trait-style functions. + +- These functions can take multiple arguments, but usually imply the user is + doing more of the work than a usual constructor would. + + `new` is still preferred for most constructor-style functions, the implication + for `from` is transformation of one data type to another. + +- Ask: What will `from_iter` do? + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md new file mode 100644 index 000000000000..aa5f522fc5b5 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md @@ -0,0 +1,29 @@ +--- +Minutes: 2 +--- + +# Into + +Prefix for a type transformation style method. + +```rust +Vec::into_parts +Cell::into_inner +IntoIter::into_iter +``` + +
+- Prefix for a function that consumes an owned value and transforms it into a value of another type. + +Not reinterpret cast! The data can be rearranged, reallocated, changed in any +way, including losing information. + +- corollary to `From` + +- `into_iter` consumes a collection (like a vec, or a btreeset, or a hashmap) + and produces an iterator over owned values, unlike `iter` and `iter_mut` which + produce iterators over reference values. + +- Ask the class: what will `Vec::into_parts` do? + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md new file mode 100644 index 000000000000..91a570d35ff4 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md @@ -0,0 +1,21 @@ +--- +minutes: 2 +--- + +# Owned + +Suffix for functions and methods about owned values in a context where +references are common. + +``` +String::to_owned +Cow::into_owned +``` + +
+- Most often seen in to_owned methods, especially on strings. + +Some exceptions, such as Cow (copy on write) having an `into_owned` method that +consumes the Cow and produces an owned value via the `ToOwned` trait. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md new file mode 100644 index 000000000000..e8242a604009 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md @@ -0,0 +1,25 @@ +--- +minutes: 2 +--- + +# By + +Component for methods that take a custom projection or comparison function. + +```rust +slice::sort_by +// caches the projection +slice::sort_by_key +Iterator::min_by +``` + +
+- Method will take a projection function. + +- Most often seen in methods that sort or otherwise manipulate a slice with a + custom sort or comparison function rather than by the `Ord` implementation of + the type itself. + +- Contradiction: `advance_by` iterator method (nightly feature) + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md new file mode 100644 index 000000000000..a07e7e190872 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md @@ -0,0 +1,25 @@ +--- +minutes: 2 +--- + +# Unchecked + +Component for methods and functions where users need to manage safety manually. + +```rust +NonNull::new_unchecked +Vec::split_at_unchecked +``` + +
+- Function is likely only callable in an unsafe block, or does not perform any runtime checks even in debug compilation. + +- Users must be careful when using these functions, as they are responsible for + making sure invariants are maintained. + +- Inputs that do not maintain expected invariants, like passing a nullptr to + NonNull::new_unchecked, will result in undefined behavior. + +- Methods with this should have a "safety" comment in their documentation + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md new file mode 100644 index 000000000000..26a7d756e480 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md @@ -0,0 +1,29 @@ +--- +minutes: 2 +--- + +# To + +Prefix to a function that takes a borrowed value and creates an owned value + +```rust +String::to_owned // &str -> String (&str is not consumed) +``` + +
+- Method for a function from a borrowed value to owned value. + +Not an escape hatch to make something borrowed into something owned, instead +creates a new owned value. + +May transform the data in some way! May return an entirely different type. This +is what makes it different from clone. + +Example: to_uppercase creates a version of a string with all uppercase letters. + +- Tends to not consume source value. + +- Also seen in functions that convert the endianness of primitives, or copy and + expose the value of a newtype. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md new file mode 100644 index 000000000000..b702260ce397 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md @@ -0,0 +1,38 @@ +--- +minutes: 5 +--- + +# As and Ref + +As is a prefix for getting a reference to something internal. Ref is a suffix. + +```rust,no_compile +Option::as_ref // &Option -> Option<&T> +Option::as_slice // &Option -> &[T] (0 or 1 elements) +OwnedFd::as_fd // &'a OwnedFd -> BorrowedFd<'a> (we'll see this later!) +Rc::as_ptr // &Rc -> *const T +Vec::as_ptr // &Vec -> *const T +``` + +
+- Method for getting a reference-style value from an owned or borrowed value. + +- Often used for getting something internal to a type. + + Collection and smart pointer types often have an `as_ptr` method, giving + access to the pointer of the value they contain. + +- Does not consume the value! Main difference between this and `to` or `into` + functions. + +- Highlight: OwnedFd::as_fd duplicates a file descriptor while tying ownership + of that descriptor to the original OwnedFd. + + This gets covered later! Don't worry about this for now. + +- Ref is a common suffix with `as`-named functions. + + `as_ref` is often a transformation of a reference to a container type (such as + option) to an owned container of reference types. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md new file mode 100644 index 000000000000..bf5a3a2ce2a0 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md @@ -0,0 +1,32 @@ +--- +minutes: 10 +--- + +Mini-exercise + +1. What do these names imply they do? +2. What should we name these signatures? + +```rust,compile_fail +// What are the types for these methods? +Option::is_some // ? +Slice::get // ? +Slice::get_unchecked_mut // ? +Option::as_ref // ? + +// What should we name methods with these types? +fn ____(String) -> Self; +fn ____(&self) -> Option<&InnerType>; // details for InnerType do not matter. +fn ____(self, String) -> Self; +fn ____(&mut self) -> Option<&mut InnerType>; +``` + +
+ +- Go through the methods in the example with the class and discuss what the + types of the functions should be. + +- Go through the unnamed methods and brainstorm what names those methods should + have. + +
From e79081eb69d9e967f9c94c7de44fcf7ac56b3076 Mon Sep 17 00:00:00 2001 From: tall-vase <228449146+tall-vase@users.noreply.github.com> Date: Tue, 9 Dec 2025 09:54:03 +0000 Subject: [PATCH 2/4] Apply suggestions from code review / Meaningful Doc Comments Co-authored-by: Dmitri Gribenko --- .../meaningful-doc-comments.md | 17 ++++++++--------- 1 file changed, 8 insertions(+), 9 deletions(-) diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments.md index de7fb8c72eec..7b35ff286ac5 100644 --- a/src/idiomatic/foundations-api-design/meaningful-doc-comments.md +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments.md @@ -5,19 +5,18 @@ minutes: 5 # Meaningful Doc Comments ```rust,compile_fail -/// API for Domain // ❌ -pub mod domain {} +/// API for the client // ❌ Lacks detail +pub mod client {} -/// Function from A to B // ❌ +/// Function from A to B // ❌ Redundant fn a_to_b(a: A) -> B {...} -/// Does X // ❌ -fn do_x() {} +/// Connects to the database. // ❌ Lacks detail │ +fn connect() -> Result<(), Error> {...} ``` -Doc comments are the most common source of documentation most developers will +Doc comments are the most common form of documentation developers engage with. -It's important to write doc comments that developers will appreciate reading, -that gives them the information they are looking for and doesn't just re-state -the obvious. +Good doc comments provide information that the code, names, and types +cannot, without restating the obvious information. From 4a92f6892ef4bf410f19c2d97a3f3139ef0075d2 Mon Sep 17 00:00:00 2001 From: tall-vase Date: Tue, 9 Dec 2025 10:58:11 +0000 Subject: [PATCH 3/4] Apply feedback to the avoid redundancy slide + add the anatomy of a doc comment slide --- src/SUMMARY.md | 6 +- src/idiomatic/foundations-api-design.md | 4 + .../clarity-readability.md | 0 .../anatomy-of-a-doc-comment.md | 84 +++++++++++++++++++ .../avoid-redundancy.md | 66 +++++++++++---- 5 files changed, 144 insertions(+), 16 deletions(-) delete mode 100644 src/idiomatic/foundations-api-design/clarity-readability.md create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments/anatomy-of-a-doc-comment.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index d9f89f076291..8a865e11c895 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -438,11 +438,12 @@ - [Welcome](idiomatic/welcome.md) - [Foundations of API Design](idiomatic/foundations-api-design.md) - [Meaningful Doc Comments](idiomatic/foundations-api-design/meaningful-doc-comments.md) - - [Avoid Redundancy](idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md) + - [Who Are You Writing For?](idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md) + - [Anatomy of a Doc Comment](idiomatic/foundations-api-design/meaningful-doc-comments/anatomy-of-a-doc-comment.md) - [Name Drop and Signpost](idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md) + - [Avoid Redundancy](idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md) - [Name and Signature are Not Enough](idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md) - [What and Why, not How and Where](idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md) - - [Who Are You Writing For?](idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md) - [Predictable API](idiomatic/foundations-api-design/predictable-api.md) - [Naming conventions](idiomatic/foundations-api-design/predictable-api/naming-conventions.md) - [Get](idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md) @@ -455,6 +456,7 @@ - [Into](idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md) - [Owned](idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md) - [By](idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md) + - [Unchecked](idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md) - [To](idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md) - [As and Ref](idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md) - [Mini Exercise](idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md) diff --git a/src/idiomatic/foundations-api-design.md b/src/idiomatic/foundations-api-design.md index ab32b5a95bae..c31a52ef740f 100644 --- a/src/idiomatic/foundations-api-design.md +++ b/src/idiomatic/foundations-api-design.md @@ -1,3 +1,7 @@ --- minutes: 2 --- + +# Foundations of API Design + +{{%segment outline}} diff --git a/src/idiomatic/foundations-api-design/clarity-readability.md b/src/idiomatic/foundations-api-design/clarity-readability.md deleted file mode 100644 index e69de29bb2d1..000000000000 diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/anatomy-of-a-doc-comment.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/anatomy-of-a-doc-comment.md new file mode 100644 index 000000000000..d9633fce8ded --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/anatomy-of-a-doc-comment.md @@ -0,0 +1,84 @@ +--- +minutes: 5 +--- + +# The Anatomy of a Doc Comment + +1. A brief, one-sentence summary. +2. A more detailed explanation. +3. Special sections: code examples, panics, errors, safety preconditions. + +````rust,no_compile +/// Parses a key-value pair from a string. +/// +/// The input string must be in the format `key=value`. Everything before the +/// first '=' is treated as the key, and everything after is the value. +/// +/// # Examples +/// +/// ``` +/// use my_crate::parse_key_value; +/// let (key, value) = parse_key_value("lang=rust").unwrap(); +/// assert_eq!(key, "lang"); +/// assert_eq!(value, "rust"); +/// ``` +/// +/// # Panics +/// +/// Panics if the input is empty. +/// +/// # Errors +/// +/// Returns a `ParseError::Malformed` if the string does not contain `=`. +/// +/// # Safety +/// +/// Triggers undefined behavior if... +unsafe fn parse_key_value(s: &str) -> Result<(String, String), ParseError> + +enum ParseError { + Empty, + Malformed, +} +```` + +
+ +- Idiomatic Rust doc comments follow a conventional structure that makes them + easier for developers to read. + +- The first line of a doc comment is a single-sentence summary of the function. + Keep it concise. `rustdoc` and other tools have a strong expectation about + that: it is used as a short summary in module-level documentation and search + results. + +- Next, you can provide a long, multi-paragraph description of the "why" and + "what" of the function. Use Markdown. + +- Finally, you can use top-level section headers to organize your content. Doc + comments commonly use `# Examples`, `# Panics`, `# Errors`, and `# Safety` as + section titles. The Rust community expects to see relevant aspects of your API + documented in these sections. + +- Rust heavily focuses on safety and correctness. Documenting behavior of your + code in case of errors is critical for writing reliable software. + +- `# Panics`: If your function may panic, you must document the specific + conditions when that might happen. Callers need to know what to avoid. + +- `# Errors`: For functions returning a `Result`, this section explains what + kind of errors can occur and under what circumstances. Callers need this + information to write robust error handling logic. + +- **Question:** Ask the class why documenting panics is so important in a + language that prefers returning `Result`. + + - **Answer:** Panics are for unrecoverable, programming errors. A library + should not panic unless a contract is violated by the caller. Documenting + these contracts is essential. + +- `# Safety` comments document safety preconditions on unsafe functions that + must be satisfied, or else undefined behavior might result. They are discussed + in detail in the Unsafe Rust deep dive. + +
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md index 9127495e9709..1fd1f06cf528 100644 --- a/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md @@ -4,19 +4,42 @@ minutes: 15 # Avoiding Redundancy -Function names and type signatures already document some information, avoid -repeating them! +Names and type signatures communicate a lot of information, don't repeat it in +comments! -```rust -// Don't do this! +```rust,compile_fail +// Repeats name/type information. Can omit! /// Parses an ipv4 from a str. Returns an option for failure modes. fn parse_ip_addr_v4(input: &str) -> Option { ... } -// TODO: couple more of these, for the instructor to go through with students. +// Repeats information obvious from the field name. Can omit! +struct BusinessAsset { + /// The customer id. + let customer_id: u64, +} + +// Mentions the type name first thing, don't do this! +/// `ServerSynchronizer` is an orchestrator that sends local edits [...] +struct ServerSynchronizer { ... } + +// Better! Focuses on purpose. +/// Sends local edits [...] +struct ServerSynchronizer { ... } + +// Mentions the function name first thing, don't do this! +/// `sync_to_server` sends local edits [...] +fn sync_to_server(...) + +// Better! Focuses on function. +/// Sends local edits [...] +fn sync_to_server(...) ```
-- Motivation: Documentation that repeats name/signature information provides nothing new to the API user. +- Motivation: Documentation that merely repeats name/signature information provides nothing new to the API user. + +Additionally, signature information may change over time without the +documentation being updated accordingly! - This is an understandable pattern to fall into! @@ -26,30 +49,45 @@ fn parse_ip_addr_v4(input: &str) -> Option { ... } Tests might enforce documentation coverage, this kind of documentation is an easy fix. -- The name of a function or type is part of the documentation of that function - or type. +- The name of an item is part of the documentation of that item. Similarly, the signature of a function is part of the documentation of that function. - Therefore: aspects of the subject are already covered when you start writing + Therefore: Some aspects of the item are already covered when you start writing doc comments! + Do not feel you need to repeat information for the sake of a bullet point + list. + - Many areas of the standard library have minimal documentation because the name and types do give enough information. Rule of Thumb: What information is missing from a user's perspective? Other than name, signature, and irrelevant details of the implementation. -- Don't drop down to language basics! Assume the reader of doc comments has an - intermediate understanding of the language itself, it's the API you're working - on that you're trying to document. +- Don't explain the basics of Rust or the standard library. Assume the reader of + doc comments has an intermediate understanding of the language itself. Focus + on documenting your API. + + For example, if your function returns `Result`, you don't need to explain how + `Result` or the question mark operators work. - If there is a complex topic involved with the functions and types you're - documenting, signpost to a "source of truth" if one exists such as a blog - post, an internal document, a paper etc. + documenting, signpost to a "source of truth" if one exists such as an internal + document, a paper, a blog post etc. - Collaborate with Students: Go through the methods in the slide and discuss what might be relevant to an API user. +## More to Explore + +- The `#![warn(missing_docs)]` lint can be helpful for enforcing the existence + of doc comments, but puts a large burden on developers that could lead to + leaning onto these patterns of writing low-quality comments. + + This kind of lint should only be enabled if the people maintaining a project + can afford to keep up with its demands, and usually only for library-style + crates rather than application code. +
From 75c73cff47ac5b69a5b2a427d5d64ee9fb20d9fb Mon Sep 17 00:00:00 2001 From: tall-vase Date: Fri, 12 Dec 2025 14:13:06 +0000 Subject: [PATCH 4/4] Apply feedback, expand some minor slides --- src/SUMMARY.md | 13 +++- .../meaningful-doc-comments.md | 7 +- .../avoid-redundancy.md | 19 +++-- .../meaningful-doc-comments/exercise.md | 51 ++++++++++++ .../library-vs-application-docs.md | 43 ++++++++++ .../name-drop-signpost.md | 38 +++++++-- .../meaningful-doc-comments/what-isnt-docs.md | 44 ++++++++++- .../what-why-not-how-where.md | 53 ++++++++++--- .../who-are-you-writing-for.md | 37 ++++++++- .../predictable-api/common-traits/05-clone.md | 4 +- .../naming-conventions/01-get.md | 22 +++--- .../naming-conventions/02-push.md | 26 +++---- .../naming-conventions/03-is.md | 28 ++++--- .../naming-conventions/04-mut.md | 20 +++-- .../naming-conventions/05-try.md | 24 +++--- .../naming-conventions/06-with.md | 18 +++-- .../naming-conventions/07-from.md | 44 +++++++++-- .../naming-conventions/08-into.md | 20 +++-- .../naming-conventions/09-owned.md | 21 ----- .../naming-conventions/10-by.md | 52 +++++++++++-- .../naming-conventions/11-unchecked.md | 57 +++++++++++--- .../naming-conventions/12-to.md | 47 +++++++++-- .../naming-conventions/13-as-and-ref.md | 78 ++++++++++++++----- .../naming-conventions/14-mini-exercise.md | 29 ++++++- .../naming-conventions/into_inner.md | 46 +++++++++++ .../predictable-api/naming-conventions/new.md | 31 ++++++++ .../naming-conventions/raw_parts.md | 32 ++++++++ .../naming-conventions/with-closure.md | 29 +++++++ .../naming-conventions/with-constructor.md | 33 ++++++++ .../naming-conventions/with-copy-setter.md | 29 +++++++ .../naming-conventions/with-word.md | 37 +++++++++ 31 files changed, 853 insertions(+), 179 deletions(-) create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments/exercise.md create mode 100644 src/idiomatic/foundations-api-design/meaningful-doc-comments/library-vs-application-docs.md delete mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/into_inner.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/new.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/raw_parts.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-closure.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-constructor.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-copy-setter.md create mode 100644 src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-word.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index 8a865e11c895..90e140457464 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -439,27 +439,34 @@ - [Foundations of API Design](idiomatic/foundations-api-design.md) - [Meaningful Doc Comments](idiomatic/foundations-api-design/meaningful-doc-comments.md) - [Who Are You Writing For?](idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md) + - [Library vs Application docs](idiomatic/foundations-api-design/meaningful-doc-comments/library-vs-application-docs.md) - [Anatomy of a Doc Comment](idiomatic/foundations-api-design/meaningful-doc-comments/anatomy-of-a-doc-comment.md) - [Name Drop and Signpost](idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md) - [Avoid Redundancy](idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md) - [Name and Signature are Not Enough](idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md) - [What and Why, not How and Where](idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md) + - [Exercise](idiomatic/foundations-api-design/meaningful-doc-comments/exercise.md) - [Predictable API](idiomatic/foundations-api-design/predictable-api.md) - [Naming conventions](idiomatic/foundations-api-design/predictable-api/naming-conventions.md) + - [New](idiomatic/foundations-api-design/predictable-api/naming-conventions/new.md) - [Get](idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md) - [Push](idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md) - [Is](idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md) - [Mut](idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md) + - [With: Constructor](idiomatic/foundations-api-design/predictable-api/naming-conventions/with-constructor.md) + - [With: Copy-and-change](idiomatic/foundations-api-design/predictable-api/naming-conventions/with-copy-setter.md) + - [With: Closures](idiomatic/foundations-api-design/predictable-api/naming-conventions/with-closure.md) + - [With in normal use](idiomatic/foundations-api-design/predictable-api/naming-conventions/with-word.md) - [Try](idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md) - - [With](idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md) - [From](idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md) - [Into](idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md) - - [Owned](idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md) + - [Into inner](idiomatic/foundations-api-design/predictable-api/naming-conventions/into_inner.md) - [By](idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md) - [Unchecked](idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md) - [To](idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md) - [As and Ref](idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md) - - [Mini Exercise](idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md) + - [Raw parts](idiomatic/foundations-api-design/predictable-api/naming-conventions/raw_parts.md) + - [Exercise](idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md) - [Implementing Common Traits](idiomatic/foundations-api-design/predictable-api/common-traits.md) - [Debug](idiomatic/foundations-api-design/predictable-api/common-traits/01-debug.md) - [PartialEq and Eq](idiomatic/foundations-api-design/predictable-api/common-traits/02-partialeq-eq.md) diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments.md index 7b35ff286ac5..41dd8555d2bb 100644 --- a/src/idiomatic/foundations-api-design/meaningful-doc-comments.md +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments.md @@ -15,8 +15,7 @@ fn a_to_b(a: A) -> B {...} fn connect() -> Result<(), Error> {...} ``` -Doc comments are the most common form of documentation developers -engage with. +Doc comments are the most common form of documentation developers engage with. -Good doc comments provide information that the code, names, and types -cannot, without restating the obvious information. +Good doc comments provide information that the code, names, and types cannot, +without restating the obvious information. diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md index 1fd1f06cf528..2aefebaf5558 100644 --- a/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/avoid-redundancy.md @@ -36,7 +36,9 @@ fn sync_to_server(...) ```
-- Motivation: Documentation that merely repeats name/signature information provides nothing new to the API user. + +- Motivation: Documentation that merely repeats name/signature information + provides nothing new to the API user. Additionally, signature information may change over time without the documentation being updated accordingly! @@ -46,8 +48,16 @@ documentation being updated accordingly! Naive approach to "always document your code," follows this advice literally but does not follow the intent. - Tests might enforce documentation coverage, this kind of documentation is an - easy fix. + Some tools might enforce documentation coverage, this kind of documentation is + an easy fix. + +- Be aware of the purpose of different modes of documentation: + + - Library code will need to be documented in ways that understand the scope of + what it is used for and the breadth of people who are trying to use it. + + - Application code has a more narrow purpose, it can afford to be more simple + and direct. - The name of an item is part of the documentation of that item. @@ -57,8 +67,7 @@ documentation being updated accordingly! Therefore: Some aspects of the item are already covered when you start writing doc comments! - Do not feel you need to repeat information for the sake of a bullet point - list. + Do not repeat information for the sake of an itemized list. - Many areas of the standard library have minimal documentation because the name and types do give enough information. diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/exercise.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/exercise.md new file mode 100644 index 000000000000..b3cf22f85e34 --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/exercise.md @@ -0,0 +1,51 @@ +--- +minutes: 10 +--- + +# Exercise: Dialog on Details + +Unnecessary details can sometimes be indicative of something that does need +documentation. + +```rust +/// Sorts a slice. Implemented using recursive quicksort. +fn sort_quickly(to_sort: &mut [T]) { /* ... */ +} +``` + +
+ +- Consider the example here, we discussed in + [what and why, not how and where](what-why-not-how-where.md) that internal + details are unlikely relevant to someone reading documentation. + + Here we're discussing a counterexample. + +- Ask the class: Is this comment necessary for this function? + +- Narrative: Playing the part of an intermediary between the class and the + author, such as a PM, manager, etc. tell the class that the author of this + function is pushing back. + +- Ask the class: Why would an author of this kind of comment push back? + + If the class asks why the author is pushing back, do not give details yet. + +- Ask the class: Why would the caller need to know the sorting algorithm in use? + +- Narrative: "Come back" from a meeting with the original author, explain to the + class that this function is application code that is called on untrusted data + that + [could be crafted maliciously to cause quadratic behavior during sorting](https://www.cs.dartmouth.edu/~doug/mdmspe.pdf). + +- Ask the class: Now we have more detail, how should we comment this function? + + The point being implementation detail vs not depends a lot on what the public + contract is (e.g., can you supply untrusted data or not), and this requires + careful judgement. + + Consider if a comment is explaining that a for-loop is used (unnecessary + detail) or if it is explaining that the algorithms used internally have known + exploits (documentation draws attention to the wrong thing). + +
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/library-vs-application-docs.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/library-vs-application-docs.md new file mode 100644 index 000000000000..f74ce73211b8 --- /dev/null +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/library-vs-application-docs.md @@ -0,0 +1,43 @@ +--- +minutes: 10 +--- + +# Library vs application docs + +You might see elaborate documentation for fundamental APIs that repeats the\ +names and type signatures. Stable and highly reusable code can afford this with\ +a positive RoI. + +- Library code: + - has a high number of users, + - solves a whole range of related problems, + - often has stable APIs. + +- Application code is the opposite: + - few users, + - solves a specific problem, + - changes often. + +
+ +- You might have seen elaborate documentation that repeats code, looks at the\ + same API multiple times with many examples and case studies. Context is key:\ + who wrote it, for whom, and what material it is covering, and what resources\ + did they have. + +- Fundamental library code often has Elaborate documentation, for example,\ + the standard library, highly reusable frameworks like serde and tokio.\ + Teams responsible for this code often have appropriate resources to write and\ + maintain elaborate documentation. + +- Library code is often stable, so the community is going to extract a\ + significant benefit from elaborate documentation before it needs to be\ + reworked. + +- Application code has the opposite traits: it has few users, solves a specific\ + problem, and changes often. For application code elaborate documentation\ + quickly becomes outdated and misleading. It is also difficult to extract a\ + positive RoI from boilerplate docs even while they are up to date, because\ + there are only a few users. + +
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md index be513a295f88..9a262abb7d58 100644 --- a/src/idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/name-drop-signpost.md @@ -5,13 +5,40 @@ minutes: 15 # Name-dropping keywords and signposting topics ```rust -/// This function covers , for further reading see: reference A, B, C. -fn highly_specific_function(/* */) { /* ... */ +/// A parsed representation of a MARC 21 record +/// [leader](//www.loc.gov/marc/bibliographic/bdleader.html). +/// A MARC leader contains metadata that dictates how to interpret the rest +/// of the record. +pub struct Leader { + /// Determines the schema and the set of valid subsequent data fields. + /// + /// Encoded in byte 6 of the leader. + pub type_of_record: char, + + /// Indicates whether to parse relationship fields, such as a "773 Host + /// Item Entry" for an article within a larger work. + /// + /// Encoded in byte 7 of the leader. + pub bibliographic_level: char, + // ... other fields } + +/// Parses the [leader of a MARC 21 record](https://www.loc.gov/marc/bibliographic/bdleader.html). +/// +/// The leader is encoded as a fixed-length 24-byte field, containing metadata +/// that determines the semantic interpretation of the rest of the record. +pub fn parse_leader(leader_bytes: &[u8; 24]) -> Result { + todo!() +} + +#[derive(Debug)] +pub enum MarcError {} ```
-- Motivation: Readers of documentation will not be closely reading most of your doc comments like they would dialogue in a novel they love. + +- Motivation: Readers of documentation will not be closely reading most of your + doc comments like they would dialogue in a novel they love. Users will most likely be skimming and scan-reading to find the part of the documentation that is relevant to whatever problem they're trying to solve in @@ -22,7 +49,7 @@ they will begin to search for context surrounding what is being documented. - Ask the class: What do you look for in documentation? Focus on the moment-to-moment searching for information here, not general values in - documentation + documentation. - Name-drop keywords close to the beginning of a paragraph. @@ -30,7 +57,8 @@ they will begin to search for context surrounding what is being documented. out the most. Skimming and scanning lets users quickly navigate a text, keeping keywords as - close to the beginning of a paragraph as possible lets a user + close to the beginning of a paragraph as possible lets a user determine if + they've found relevant information faster. - Signpost, but don't over-explain. diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md index e67b4d453485..d846df4a2158 100644 --- a/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.md @@ -5,18 +5,54 @@ minutes: 5 Names and Signatures are not full documentation ```rust +// bad +/// Returns a future that resolves when operation completes. +fn syncToServer() -> Future + +// good +/// Sends local edits to the server, overwriting concurrent edits +/// if any happened. +fn syncToServer() -> Future +// bad +/// Returns an error if sending the email fails. +fn send(&self, email: Email) -> Result<(), Error> + +// good +/// Queues the email for background delivery and returns immediately. +/// Returns an error immediately if the email is malformed. +fn send(&self, email: Email) -> Result<(), Error> ```
-- Motivation: API designers can over-commit to the idea that a function name and signature is enough documentation. + +- Motivation: API designers can over-commit to the idea that a function name and + signature is enough documentation. It's better than nothing, but it's worse than good documentation. - Again, names and types are _part_ of the documentation. They are not always the full story! -- TODO: give some rules of thumb for when to go into more detail, - cross-reference rust stdlib docs. This may live better in the name conventions - area. +- Consider the behavior of functions that are not covered by the name, parameter + names, or signature of that function. + + In the example on the slide it is not obvious that `syncToServer()` could + overwrite something (leading to a data loss), so document that. + + In the email example, it is not obvious that the function can return success + and still fail to deliver the email. + +- Use comments to disambiguate. Nuanced behaviors, behaviors that users of an + API could trip up on, should be documented. + + For example, consider a remove() method on a business entity: There are many + ways to remove an entity! + + Is it removing the entity from the database? From the parent collection in + memory (unlink vs erase)? + + If it is removing the data in the database, is the data actually being + deleted, or merely marked as deleted, but still recoverable (soft vs hard + delete)?
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md index 9eeb41f7f7d1..579a2e95dc8d 100644 --- a/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/what-why-not-how-where.md @@ -8,20 +8,54 @@ Avoid documenting irrelevant details that may frequently change. ```rust,no_compile /// Sorts a slice. Implemented using recursive quicksort. + fn sort_quickly(to_sort: &mut [T]) { /* ... */ } -/// Calls an org-internal service using reqwest. -fn ask_service(url: &str) -> String { /* ... */ +// bad +/// Saves a `User` record to the Postgres database. +/// +/// This function opens a new connection and begins a transaction. It checks +/// if a user with the given ID exists with a `SELECT` query. If a user is +/// not found, performs an `INSERT`. +/// +/// # Errors +/// +/// Returns an error if any database operation fails. +pub fn save_user(user: &User) -> Result<(), db::Error> { + // ... +} + +// good +/// Atomically saves a user record. +/// +/// # Errors +/// +/// Returns a `db::Error::DuplicateUsername` error if the user (keyed by +/// `user.username` field) already exists. +pub fn save_user(user: &User) -> Result<(), db::Error> { + // ... } ```
-- Motivation: Using doc comments to explain how a function does something internally means if that internal implementation detail changes, the doc comment needs to change as well. -Internal information is likely irrelevant to a user. Imagine explaining in a doc -comment for a function that you're using for loops to solve a problem, what is -the point of this information? +- Motivation: Users want to know the contract of the API (what is guaranteed + about this function), rather than implementation details. + +- Motivation: Doc comments that explain implementation details become outdated + faster than comments that explain the contract. + + Internal information is likely irrelevant to a user. Imagine explaining in a + doc comment for a function that you're using for loops to solve a problem, + what is the point of this information? + +- Consider the `sort_quickly` function above. Its documentation calls out that + it uses quicksort, but is this necessary? + + It could be that another sorting function is used in the future, if that were + the case then this comment would need to be updated too. This is a point of + failure in documentation. - It could be that the implementation is necessary to explain, but this is likely due to whatever effects or invariants the user of that API needs to be @@ -33,14 +67,11 @@ the point of this information? Reiterate: Implementation details can and will change, so do not explain these details. - TODO: Real-life example of something appropriate to a large system. - - Don't talk about where something is used for the sake of it. This is another instance where this information can become stale quickly. -- Prefer instead to focus on what the function does (though again, not how it is - implemented) for a user trying to reach this practical information as quickly - as possible. +- Focus on what the function does (not how it is implemented) for a user trying + to reach this practical information as quickly as possible.
diff --git a/src/idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md b/src/idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md index 6f7545283c3e..1c2b0da123c6 100644 --- a/src/idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md +++ b/src/idiomatic/foundations-api-design/meaningful-doc-comments/who-are-you-writing-for.md @@ -7,11 +7,38 @@ minutes: 10 Colleagues, collaborators, largely-silent API users, or just yourself? ```rust -// TODO: What's a good illustration here? +// expert writes for experts +/// Canonicalizes the MIR for the borrow checker. +/// +/// This pass ensures that all borrows conform to the NLL-Polonius constraints +/// before we proceed to MIR-to-LLVM-IR translation. +pub fn canonicalize_mir(mir: &mut Mir) { + // ... +} + +// expert writes for newcomers +/// Prepares the Mid-level IR (MIR) for borrow checking. +/// +/// The borrow checker operates on a simplified, "canonical" form of the MIR. +/// This function performs that transformation. It is a prerequisite for the +/// final stages of code generation. +/// +/// For more about Rust's intermediate representations, see the +/// [rustc-dev-guide](https://rustc-dev-guide.rust-lang.org/mir/index.html). +pub fn canonicalize_mir(mir: &mut Mir) { + // ... +} ```
-- Motivation: It can be easy to fall into a pattern of writing only for you, but most documentation is for people coming in with a different perspective. + +- Background: The + [curse of knowledge](https://en.wikipedia.org/wiki/Curse_of_knowledge) is a + cognitive bias where experts assume that others have the same level of + expertise and perspective. + +- Motivation: Your reader does not have the same level of expertise and the same + perspective as you. Don't write for people like yourself, write for others. - Unintentionally writing for yourself can lead to people not understanding a point you're trying to make or the concept you're trying to articulate. @@ -27,8 +54,14 @@ Colleagues, collaborators, largely-silent API users, or just yourself? - Also imagine a version of you, or others you've known, who is struggling to find the important details in winding, extensive doc comments. Don't give too much information. + - Always ask: Is this documentation making it difficult for the API user? Are they able to quickly grasp what they need or find out where they could need it? +- Always consider: Experts also read API level documentation. Doc comments might + not be the right place to educate your audience about the basics of your + domain. In that case, signpost and name-drop. Divert people to long-form + documentation. +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md b/src/idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md index 67070b21dd7c..1a827fd79ee0 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md +++ b/src/idiomatic/foundations-api-design/predictable-api/common-traits/05-clone.md @@ -40,7 +40,9 @@ let reference_copied = reference_counted.clone(); ```
-- Deep clones a value, or in the case of smart pointers like `Rc`/`Arc` create a new instance of that pointer. + +- "Deep copy" a value, or in the case of reference counting pointers like + `Rc`/`Arc` create a new instance of that pointer. - When to not implement/derive: For types that, to maintain an invariant, the value should not be duplicated. We'll touch on this later in Idiomatic Rust. diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md index 25aac6450d88..c2ad2d28d74a 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/01-get.md @@ -2,17 +2,18 @@ minutes: 2 --- -# Get +# `get`: Borrow an Element Getting an element from a collection or container. -```rust -// Safe, fallible indexing. -let items: Vec = vec![1, 2, 3]; -let option = items.get(0); // &Vec -> Option<&u8> -assert_eq!(Some(1), option); -let failed_option = items.get(1000); // &Vec -> Option<&u8> -assert_eq!(None, option); +```rust,no_compile +impl Vec { + fn get(&self, index: usize) -> Option<&T> {...} +} + +impl OnceCell { + fn get(&self) -> Option<&T> {...} +} ```
@@ -24,8 +25,7 @@ Should not panic. May return an option or result, depending on the framework. - Not for fields! - For private fields you don't want users to have direct, assign-level access t - a method with a more descriptive name (or the same name as the field) is - preferred. + For private fields you don't want users to have direct, assign a method with a + more descriptive name (or the same name as the field) is preferred.
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md index 9edc82e9822c..0f4327d9ba3f 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/02-push.md @@ -2,28 +2,22 @@ minutes: 2 --- -# Push +# `push` Common on array-like structures. ```rust -use std::collections::VecDeque; +impl Vec { + fn push(&mut self, value: T) +} -let mut items: Vec = Vec::new(); -items.push(42); -let mut items_queue: VecDeque = VecDeque::new(); -items_queue.push_front(233); -// [233] -items_queue.push_back(42); -// [233, 42] -items_queue.push_front(128); -// [128, 233, 42] -dbg!(items_queue); +impl VecDeque { + fn push_back(&mut self, value: T) + fn push_front(&mut self, value: T) +} ```
-- Modifies an array-like structure by adding an element. +- Modifies a sequential collection by adding an element. -Needs mutable access! - -
+- Takes `self` by mutable reference. diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md index f03e3432562b..1223886c0172 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/03-is.md @@ -2,26 +2,30 @@ minutes: 2 --- -# Is +# `is_[condition]`: Boolean Check Check a condition about a datatype. -```rust -// TODO: Should this just be no-compile versions that -dbg!("".is_empty()); -dbg!(vec![1u32].is_empty()); -dbg!(f32::NAN.is_nan()); -// No is_not_nan method, don't write these kinds of methods! -dbg!(!0.99.is_nan()); -dbg!(64u32.is_power_of_two()); +```rust,no_compile +impl Vec { + is_empty(&self) -> bool +} + +impl f32 { + is_nan(self) -> bool +} + +impl u32 { + is_power_of_two(self) -> bool +} ```
- A boolean condition on a value. -`is` prefix is preferred over methods with `not` in the name. +- `is` prefix is preferred over methods with `not` in the name. -There are no instances of `is_not_` in standard library methods, just use -`!value.is_`. + There are no instances of `is_not_` in standard library methods, just use + `!value.is_[condition]`.
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md index eac0940c1f01..2784914ce563 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/04-mut.md @@ -2,16 +2,24 @@ minutes: 2 --- -# Mut +# `[method]_mut`: Mutable reference access Suffix for access-style methods. ```rust -Vec::get_mut -// Iterate over a slice by mutable reference, being able to mutate -// items in the iterator as you iterate over them. -slice::iter_mut -RefCell::get_mut +impl Vec { + // Simplified + fn get_mut(&mut self, usize) -> Option<&T> +} + +impl [T] { + // Simplified + fn iter_mut(&mut self) -> impl Iterator +} + +impl str { + fn from_utf8_mut(v: &mut [u8]) -> Result<&mut str, Utf8Error> +} ```
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md index 12b8b3441343..d90fa48d7126 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/05-try.md @@ -2,11 +2,19 @@ minutes: 2 --- -# Try +# `try_[method]`: Fallible methods with Specific Errors Prefix for fallible methods that return a `Result`. -```rust +```rust,no_compile +impl TryFrom for u32 { + type Error = TryFromIntError; + fn try_from(value: i32) -> Result +} + +impl Receiver { + try_recv(&self) -> Result +} ```
@@ -15,13 +23,11 @@ Prefix for fallible methods that return a `Result`. - `TryFrom` is a `From`-like trait for types whose single-value constructors might fail in some way. -- Ask: Why aren't `Vec::get` and other similar methods `try_get`? - - There's only one possible error with get-style methods, out-of-bounds or - key-does-not-exist style access errors. +- Ask: Why aren't `Vec::get` and other similar methods called `try_get`? - Also: get-style methods will be used frequently with data types like hash - maps, sets. `get` is shorter and faster to scan visually than try_get, if try - were more prolific. + Methods are named `get` if they return a reference to an existing value and + return an `Option` instead of `Result` because there is only one failure mode. + For example, only "index out of bounds" for `Vec::get`, and "key does not + exist" for `HashMap::get`.
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md index 89bea4fc556a..2cc7a27da33a 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/06-with.md @@ -2,18 +2,24 @@ minutes: 5 --- -# With +# `with` -Prefix for builder-style configuration. +Prefix for various setter and constructor style functions. ```rust -{Vec, BTreeSet}::with_capacity -PathBuf::with_extension -PathBuf::with_file_name +impl Vec { + // Constructor style. + fn with_capacity(capacity: usize) -> Vec; +} + +impl Path { + // Simplified. Clone-And-Set style. + fn with_extension(&self, ext: &OsStr) -> Path; +} ```
-- Prefix for methods that set something internally. +- Prefix for methods that create a new copy of a data structure. Can be constructors, builders, or setters. diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md index 9bbe0c29825e..ce2ef73ae53a 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/07-from.md @@ -2,13 +2,30 @@ minutes: 2 --- -# From +# `from` -Prefix for a constructor-style function. +A constructor function, strongly implying "type conversion". ```rust -// TODO: more examples -Vec::from_raw_parts, from_iter, from_le_bytes +impl CStr { + unsafe fn from_ptr<'a>(ptr: *const i8) -> &'a CStr; +} + +impl Duration { + fn from_days(days: u64) -> Duration; +} + +impl Vec { + fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec; +} + +impl i32 { + fn from_ascii(src: &[u8]) -> Result; +} + +impl u32 { + fn from_le_bytes(bytes: [u8; 4]) -> u32; +} ```
@@ -20,6 +37,23 @@ Vec::from_raw_parts, from_iter, from_le_bytes `new` is still preferred for most constructor-style functions, the implication for `from` is transformation of one data type to another. -- Ask: What will `from_iter` do? +- Ask: Without looking at the standard library documentation, what would the + argument type of `u32::from_be` be? + + Answer guidance: we already see `u32::from_le_bytes` on the slide, it takes a + slice of bytes. So from_le must be simpler, taking not bytes. Think about the + contrast between `u32` and `be`. The argument must be a big-endian `u32`! + + Follow-up question: How about `str::from_utf8`? + + Answer guidance: `str` vs `utf8`. The argument can't be a `str` because every + `str` is valid UTF-8. So what is the simplest way to provide UTF-8 data? A + slice of bytes. + + Follow-up: Why not `str::from_utf8_bytes`? + + Answer: It could be in theory. However, the "omit needless words" principle + applies, the word "bytes" would merely repeat the obvious - could a UTF-8 + sequence ever be non-bytes?
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md index aa5f522fc5b5..8bf4770ab6a3 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/08-into.md @@ -1,15 +1,21 @@ --- -Minutes: 2 +minutes: 2 --- -# Into +# `into` -Prefix for a type transformation style method. +- Prefix for methods that convert `self` into another type. + +Consumes `self`, returns an owned value. ```rust -Vec::into_parts -Cell::into_inner -IntoIter::into_iter +impl Vec { + fn into_parts(self) -> (NonNull, usize, usize); +} + +impl Cell { + fn into_inner(self) -> T +} ```
@@ -24,6 +30,6 @@ way, including losing information. and produces an iterator over owned values, unlike `iter` and `iter_mut` which produce iterators over reference values. -- Ask the class: what will `Vec::into_parts` do? +- Ask the class: what will `Vec::into_raw_parts` do?
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md deleted file mode 100644 index 91a570d35ff4..000000000000 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/09-owned.md +++ /dev/null @@ -1,21 +0,0 @@ ---- -minutes: 2 ---- - -# Owned - -Suffix for functions and methods about owned values in a context where -references are common. - -``` -String::to_owned -Cow::into_owned -``` - -
-- Most often seen in to_owned methods, especially on strings. - -Some exceptions, such as Cow (copy on write) having an `into_owned` method that -consumes the Cow and produces an owned value via the `ToOwned` trait. - -
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md index e8242a604009..7a980900c650 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/10-by.md @@ -2,24 +2,60 @@ minutes: 2 --- -# By +# `by`: custom comparator or projection Component for methods that take a custom projection or comparison function. -```rust -slice::sort_by -// caches the projection -slice::sort_by_key -Iterator::min_by +```rust,compile_fail +impl [T] { + // Simplified + fn sort_by(&mut self, compare: impl FnMut(&T, &T) -> Ordering); + + // Uses a predicate to determine what items end up in non-overlapping chunks. + fn chunk_by_mut bool>( + &mut self, + pred: F, + ) -> ChunkByMut<'_, T, F>; +} + +trait Iterator { + // Provided method of Iterator. Simplified. + fn min_by( + self, + compare: impl FnMut(&Self::Item, &Self::Item) -> Ordering, + ) -> Option; +} ```
-- Method will take a projection function. +- Method will take a comparison or projection function. + +A projection function here being a function that, given a reference to a value +that exists in the data structure, will compute a value to perform the principle +computation with. + +Methods like `sort_by_key` allow us to sort by _the hash function I've passed to +the method_ or sort by _this specific field of the data in the slice_. + +For example, if you have a slice of values of some data structure you might want +to sort them by a field of that data structure, or even a hash value of that +data. + +`sort_by` takes a comparator function directly. - Most often seen in methods that sort or otherwise manipulate a slice with a custom sort or comparison function rather than by the `Ord` implementation of the type itself. -- Contradiction: `advance_by` iterator method (nightly feature) +- Sometimes the "by" preposition is simply a preposition. + + "by", like some other name components, may end up in a method name for normal + linguistic reasons rather than holding specific naming convention semantic + weight. + + - [`Read::by_ref()`](https://doc.rust-lang.org/std/io/trait.Read.html#method.by_ref) + + - [`Iterator::advance_by()`](https://doc.rust-lang.org/std/iter/trait.Iterator.html#method.advance_by) + iterator method (nightly feature)
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md index a07e7e190872..acf2ba4ed021 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/11-unchecked.md @@ -1,25 +1,58 @@ --- -minutes: 2 +minutes: 5 --- -# Unchecked +# `unchecked`: Unsafe -Component for methods and functions where users need to manage safety manually. +`unchecked` distinguishes the unsafe function in a safe/unsafe pair. -```rust -NonNull::new_unchecked -Vec::split_at_unchecked +Don't add "unchecked" to the name of every unsafe function. + +```rust,no_compile +impl NonNull { + // A checked version of the constructor, `None` on null. + fn new(ptr: *mut T) -> Option> + + // Unchecked cosntructor, you can violate the non-null invariant! + unsafe fn new_unchecked(ptr: *mut T) -> NonNull +} + +impl Vec { + // Panics on OOB, old API design. + fn split_at(&self, mid: usize) -> (&[T], &[T]) + + // Newer method, returns `None` if mid > len + fn split_at_checked(&self, mid: usize) -> Option<(&[T], &[T])> + + // Unchecked split function, splitting out of bounds is undefined behavior! + unsafe fn split_at_unchecked(&self, mid: usize) -> (&[T], &[T]) +} ```
-- Function is likely only callable in an unsafe block, or does not perform any runtime checks even in debug compilation. +- Sometimes we need to define a pair of functions that have very similar behavior, but one is safe, and the other one is unsafe. + +- Please take the Unsafe Rust deep dive if you want to learn more about unsafe + code. Briefly, unsafe functions transfer the responsibility for memory safety + from the compiler to the programmer. If misused, they can trigger undefined + behavior. + +- Rust does not overload functions on safety, so we use different names for the + functions in the pair. To make the names predictable for users, we use a + naming convention. + +- The safe function gets the short name. We add "unchecked" to the name of the + unsafe function. -- Users must be careful when using these functions, as they are responsible for - making sure invariants are maintained. +- We don't add "unchecked" to the name of every unsafe function. -- Inputs that do not maintain expected invariants, like passing a nullptr to - NonNull::new_unchecked, will result in undefined behavior. + - In Rust we don't need a naming convention to highlight the danger of unsafe + code at the callsite: Rust already requires the caller to write an + `unsafe {}` block. This is different from other languages that don't have + unsafe blocks, for example, Swift naming convention is to add the word + "unsafe" to the type and function names. -- Methods with this should have a "safety" comment in their documentation + - We only use this naming convention when we want to provide a function pair, + and therefore must use different names.
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md index 26a7d756e480..65798e0956f9 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/12-to.md @@ -2,28 +2,59 @@ minutes: 2 --- -# To +# `to`: Non-consuming Conversion Prefix to a function that takes a borrowed value and creates an owned value ```rust -String::to_owned // &str -> String (&str is not consumed) +impl str { + // &str is not consumed. + fn to_owned(&str) -> String + + fn to_uppercase(&self) -> String +} + +impl u32 { + // take an owned self because `u32` implements `Copy` + to_be(self) -> u32 +} ```
-- Method for a function from a borrowed value to owned value. +- Methods that create a new owned value without consuming `self`, and imply a type conversion, are named starting with `to`. + +- This is not a borrow checker escape hatch, or an instance of unsafe code. A + new value is created, the original data is left alone. + +- Methods that start with "to" return a different type, and strongly imply a + non-trivial type conversion, or even a data transformation. For example, + `str::to_uppercase`. -Not an escape hatch to make something borrowed into something owned, instead -creates a new owned value. +- "to" methods most commonly take `&self`. However they can take `self` by value + if the type implements `Copy`: this also ensures that the conversion method + call does not consume `self`. -May transform the data in some way! May return an entirely different type. This -is what makes it different from clone. +- If you simply want to define a method that takes `&self` and returns an owned + value of the same type, implement the `Clone` trait. Example: to_uppercase creates a version of a string with all uppercase letters. -- Tends to not consume source value. +- If you want to define a method that consumes the source value, use the "into" + naming pattern. - Also seen in functions that convert the endianness of primitives, or copy and expose the value of a newtype. +## More to Explore + +- Ask the class: What's the difference between `to_owned` and `into_owned`? + + Answer: `to_owned` appears on reference values like `&str`, whereas + `into_owned` appears on owned values that hold reference types, like `Cow` + (copy-on-write). + + Types like `Cow` can be owned while containing references that are borrowed, + so the owned value of `Cow` is consumed to create an owned value of the + reference type it was holding onto. +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md index b702260ce397..dbacc48847f3 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/13-as-and-ref.md @@ -2,37 +2,77 @@ minutes: 5 --- -# As and Ref +# `as_` and `_ref`: reference conversions -As is a prefix for getting a reference to something internal. Ref is a suffix. +`as` is a prefix for methods that convert references. `ref` is a suffix (but +prefer `as`.) + +`as` methods borrow out the primary piece of data contained in `&self`. + +Most commonly return references, but can also return a custom borrowing type or +an unsafe pointer. ```rust,no_compile -Option::as_ref // &Option -> Option<&T> -Option::as_slice // &Option -> &[T] (0 or 1 elements) -OwnedFd::as_fd // &'a OwnedFd -> BorrowedFd<'a> (we'll see this later!) -Rc::as_ptr // &Rc -> *const T -Vec::as_ptr // &Vec -> *const T +impl Rc { + fn as_ptr(&self) -> *const T; + + // Very common on container types, see how it's also on Option. + fn as_ref(&self) -> &T; +} + +impl Option { + fn as_ref(&self) -> Option<&T>; + // Slices can be empty! So this is 0 or 1 elements. + fn as_slice(&self) -> &[T]; +} + +impl OwnedFd { + // Covered later. + fn as_fd(&'a self) -> BorrowedFd<'a>; +} ```
-- Method for getting a reference-style value from an owned or borrowed value. -- Often used for getting something internal to a type. +- Method that returns a borrow of the primary piece of contained data. + +- The borrowing relationship is most often straightforward: the return value is + a reference that borrows `self`. + +- Borrowing can also be subtle, and merely implied. + + - The returned value could be a custom borrowing type, fore example, + `BorrowedFd` borrows `OwnedFd` through an explicit lifetime. + + - We cover custom borrowing types later in this deep dive, + [PhantomData: OwnedFd & BorrowedFd](../../../leveraging-the-type-system/borrow-checker-invariants/phantomdata-04-borrowedfd.md). - Collection and smart pointer types often have an `as_ptr` method, giving - access to the pointer of the value they contain. + - The returned value could borrow `self` only logically, for example, + `as_ptr()` methods return an unsafe pointer. The borrow checker does not + track borrowing for pointers. -- Does not consume the value! Main difference between this and `to` or `into` - functions. +- The type implementing an "as" method should contain one primary piece of data + that is being borrowed out. -- Highlight: OwnedFd::as_fd duplicates a file descriptor while tying ownership - of that descriptor to the original OwnedFd. + - The "as" naming convention does not work if the data type is an aggregate of + many fields without an obvious primary one. Think about the call site: - This gets covered later! Don't worry about this for now. + ```rust,compile_fail + my_vec.as_ptr() // OK + my_person.as_first_name() // does not read right, don't use "as_" + my_person.first_name() // OK + ``` -- Ref is a common suffix with `as`-named functions. + - If you want to have two getters that you need to distinguish, one that + returns first name by value, and another one that returns it by reference, + use `_ref` suffix: - `as_ref` is often a transformation of a reference to a container type (such as - option) to an owned container of reference types. + ```rust,compile_fail + impl Person { + fn first_name(&self) -> String + fn first_name_ref() -> &str + fn first_name_mut() -> &mut String + } + ```
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md index bf5a3a2ce2a0..b48ff6224055 100644 --- a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/14-mini-exercise.md @@ -2,17 +2,20 @@ minutes: 10 --- -Mini-exercise +# Exercise 1. What do these names imply they do? 2. What should we name these signatures? ```rust,compile_fail -// What are the types for these methods? +// What are the types of these methods? Option::is_some // ? -Slice::get // ? -Slice::get_unchecked_mut // ? +slice::get // ? +slice::get_unchecked_mut // ? Option::as_ref // ? +str::from_utf8_unchecked_mut // ? +Rc::get_mut // ? +Vec::dedup_by_key // ? // What should we name methods with these types? fn ____(String) -> Self; @@ -29,4 +32,22 @@ fn ____(&mut self) -> Option<&mut InnerType>; - Go through the unnamed methods and brainstorm what names those methods should have. + Answers for missing types: + - `Option::is_some(&self) -> bool` + - `slice::get(&self /* &[T] */, usize) -> Option<&T>` + - `slice::get_unchecked_mut(&self /* &[T] */, usize) -> &T` (unsafe and + simplified) + - `Option::as_ref(&self /* &Option */) -> Option<&T>` + - `str::from_utf8_unchecked_mut(v: &mut [u8]) -> &mut str` (unsafe) + - `Rc::get_mut(&mut self /* &mut Rc */) -> Option<&mut T>` (simplified) + - `Vec::dedup_by_key(&mut self /* &mut Vec */, key: impl FnMut(&mut T) -> K)` + (simplified) + + Answers for missing names: + - `fn from_string(String) -> Self` + - `fn inner(&self) -> Option<&InnerType>` or `as_ref`, depending on context + - `fn with_string(self, String) -> Self` + - `fn inner_mut(&mut self) -> Option<&mut InnerType>` or `as_ref_mut`, + depending on context +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/into_inner.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/into_inner.md new file mode 100644 index 000000000000..3d5511b7898d --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/into_inner.md @@ -0,0 +1,46 @@ +--- +minutes: 2 +--- + +# Aside: `into_inner` + +Special case of `into`: for exclusive pointer types or newtypes, extract the +internal value. + +```rust,compile_fail +pub struct Wrapper(T); + +impl Wrapper { + fn into_inner(self) -> T; +} + +pub struct NonZeroU32(u32); + +impl NonZeroU32 { + fn into_inner(self) -> u32; +} + +impl Cell { + fn into_inner(self) -> T; +} +``` + +
+ +- `into_inner` is a method usually found on newtypes: types whose main purpose + is to wrap around an existing type and be semantically distinct from other + uses of that inner type. + +This kind of method is also found on types like `Cell`, which exclusively own +the internal data. + +The purpose of this kind of method is to consume the "wrapper" type and return +the "contained" value. + +- When defining a type with exactly one field, consider if it makes sense to + implement an `into_inner` method that consumes `self` and returns the field as + an owned value. + + Don't write a method like this if more fields will be added in the future. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/new.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/new.md new file mode 100644 index 000000000000..261fce8f8d49 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/new.md @@ -0,0 +1,31 @@ +--- +minutes: 1 +--- + +# `new`: Constructor functions + +Rust does not have a `new` keyword, instead `new` is a common prefix or whole +method name. + +```rust +impl Vec { + // Creates an empty vec. + fn new() -> Vec; +} + +impl Box { + fn new(T) -> Box; +} +``` + +
+ +- There's no `new` keyword for rust to initialize a new value, only functions + you call or values you directly populate. + + `new` is conventional for the "default" constructor function for a type. It + holds no special syntactic meaning. + + This is sometimes a prefix, it sometimes takes arguments. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/raw_parts.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/raw_parts.md new file mode 100644 index 000000000000..9372096b49c4 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/raw_parts.md @@ -0,0 +1,32 @@ +--- +minutes: 2 +--- + +# `raw_parts` + +Peeling back safe abstractions on heap data. + +```rust +impl Vec { + // Note how this is an unsafe function + unsafe fn from_raw_parts(ptr: *mut T, length: usize, capacity: usize) -> Vec; + + fn into_raw_parts(self) -> (*mut T, usize, usize); +} +``` + +
+ +- `raw_parts` denotes methods that construct items from or decompose items into + underlying pointer data and its relevant layout information (capacity, etc.). + +- These kinds of methods can be marked as `unsafe` if constructing new values as + trust is placed on the user to avoid conditions that might lead to undefined + behavior. + + Such a case might be passing a pointer of `sizeof T * 10` to + `Vec::from_raw_parts` but also passing `20` as the capacity argument, which + would lead to writing or accessing values 10 through 19 in the vector being + undefined behavior. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-closure.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-closure.md new file mode 100644 index 000000000000..47dd23f7cd0a --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-closure.md @@ -0,0 +1,29 @@ +--- +minutes: 2 +--- + +# `with`: Working with Closures + +`with` as in "do X, but with this specific way of computing things." + +```rust +impl Vec { + // Simplified. If the resize is larger than the current vec size, use the + // closure to populate elements. + pub fn resize_with(&mut self, new_len: usize, f: impl FnMut() -> T); +} + +mod iter { + // Create an infinite, lazy iterator using a closure. + pub fn repeat_with A>(repeater: F) -> RepeatWith; +} +``` + +
+ +- `with` can appear as a suffix to communicate there is a specific function or + closure that can be used instead of a "sensible default" for a computation. + + Similar to [`by`](./10-by.md). + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-constructor.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-constructor.md new file mode 100644 index 000000000000..b2e5863ddb30 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-constructor.md @@ -0,0 +1,33 @@ +--- +minutes: 2 +--- + +# `with` as constructor + +`with` as a constructor sets one value among a type while using default values +for the rest. + +`with` as in "`` with specific setting." + +```rust +impl Vec { + // Initializes memory for at least N elements, len is still 0. + fn with_capacity(capacity: usize) -> Vec; +} +``` + +
+ +- `with` can appear as a constructor prefix, most commonly when initializing + heap memory for container types. + + In this case, it's distinct from `new` constructors because it specifies the + value for something that is not usually cared about by API users. + +- Ask the class: Why not `from_capacity`? + + Answer: `Vec::with_capacity` as a method call scans well as creating a "Vec + with capacity". Consider how `Vec::new_capacity` or `Vec::from_capacity` scan + when written down, they do not communicate what's going on well. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-copy-setter.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-copy-setter.md new file mode 100644 index 000000000000..4c3559c13c96 --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-copy-setter.md @@ -0,0 +1,29 @@ +--- +minutes: 2 +--- + +# `with` as copy-and-set + +`with` appears when a value is being copied, but also changed in a specific way. + +`with` as in "like ``, but with something different." + +```rust +impl Path { + // Simplified. "/home/me/mortgage.pdf".with_extension("mov") => + // "/home/me/mortgage.mov" + fn with_extension(&self, ext: &OsStr) -> PathBuf; +} +``` + +
+ +- `with` can be used for methods that copy a value, but then change a specific + part of that value. + + In the example here, `with_extension` copies the data of a `&Path` into a new + `PathBuf`, but changes the extension to something else. + + The original `Path` is unchanged. + +
diff --git a/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-word.md b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-word.md new file mode 100644 index 000000000000..173ade91a17e --- /dev/null +++ b/src/idiomatic/foundations-api-design/predictable-api/naming-conventions/with-word.md @@ -0,0 +1,37 @@ +--- +minutes: 2 +--- + +# `with` in normal use + +Sometimes a `with` is just a `with`. + +`with` when used in common English contexts. + +```rust +// impl block for slices +impl [T] { + // A condition, but doesn't start with `is`, and uses `with` as a normal word. + fn starts_with(&self, &[T]) -> bool; +} +``` + +
+ +- Name fragments are not hard rules, they are guidance. Sometimes a method's + name will include words that break its pattern. + +- In this example with have `starts_with`, which is a boolean condition that + does not start with "is" and is suffixed by "with". + + If naming conventions were to be treated as hard rules, this would fail as a + case. + + This is a good name for understanding what is going on at the callsite. We end + up writing `.starts_with()` which scans well for authors + and readers of code. + +- Remember: the point of naming conventions is predictability, and how + predictability is in service of callsite clarity and readability. + +