diff options
| author | Aleksey Kladov <aleksey.kladov@gmail.com> | 2020-08-17 16:11:29 +0200 |
|---|---|---|
| committer | Aleksey Kladov <aleksey.kladov@gmail.com> | 2020-08-17 16:11:29 +0200 |
| commit | 6a4c9fc9fd6cb9ecf08bd5a22890eb19d22ad34e (patch) | |
| tree | 8e0cf69fd3addb137fae6babdda625437078b143 /docs/dev | |
| parent | 0b2b9a5508186c16a2e782f47ce7e0e1c5fb8d33 (diff) | |
| download | rust-6a4c9fc9fd6cb9ecf08bd5a22890eb19d22ad34e.tar.gz rust-6a4c9fc9fd6cb9ecf08bd5a22890eb19d22ad34e.zip | |
Don't make fields private unless you have to
Diffstat (limited to 'docs/dev')
| -rw-r--r-- | docs/dev/style.md | 29 |
1 files changed, 29 insertions, 0 deletions
diff --git a/docs/dev/style.md b/docs/dev/style.md index 963a6d73d05..8effddcda55 100644 --- a/docs/dev/style.md +++ b/docs/dev/style.md @@ -176,6 +176,35 @@ fn frobnicate(walrus: Option<Walrus>) { } ``` +# Getters & Setters + +If a field can have any value without breaking invariants, make the field public. +Conversely, if there is an invariant, document it, enforce it in the "constructor" function, make the field private, and provide a getter. +Never provide setters. + +Getters should return borrowed data: + +``` +struct Person { + // Invariant: never empty + first_name: String, + middle_name: Option<String> +} + +// Good +impl Person { + fn first_name(&self) -> &str { self.first_name.as_str() } + fn middle_name(&self) -> Option<&str> { self.middle_name.as_ref() } +} + +// Not as good +impl Person { + fn first_name(&self) -> String { self.first_name.clone() } + fn middle_name(&self) -> &Option<String> { &self.middle_name } +} +``` + + # Premature Pessimization Avoid writing code which is slower than it needs to be. |
