diff options
author | bors[bot] <26634292+bors[bot]@users.noreply.github.com> | 2020-08-17 15:13:07 +0100 |
---|---|---|
committer | GitHub <[email protected]> | 2020-08-17 15:13:07 +0100 |
commit | 64bbdb5bc7e61d2d6ff67e722e34275ef2a47554 (patch) | |
tree | 25305a222e79648fff2363789a5047faf0d4f562 /docs/dev/style.md | |
parent | df225472762c92aec3c991a3d0f78bad5058a39b (diff) | |
parent | 6a4c9fc9fd6cb9ecf08bd5a22890eb19d22ad34e (diff) |
Merge #5785
5785: Don't make fields private unless you have to
r=matklad a=matklad
bors r+
🤖
Co-authored-by: Aleksey Kladov <[email protected]>
Diffstat (limited to 'docs/dev/style.md')
-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 963a6d73d..8effddcda 100644 --- a/docs/dev/style.md +++ b/docs/dev/style.md | |||
@@ -176,6 +176,35 @@ fn frobnicate(walrus: Option<Walrus>) { | |||
176 | } | 176 | } |
177 | ``` | 177 | ``` |
178 | 178 | ||
179 | # Getters & Setters | ||
180 | |||
181 | If a field can have any value without breaking invariants, make the field public. | ||
182 | Conversely, if there is an invariant, document it, enforce it in the "constructor" function, make the field private, and provide a getter. | ||
183 | Never provide setters. | ||
184 | |||
185 | Getters should return borrowed data: | ||
186 | |||
187 | ``` | ||
188 | struct Person { | ||
189 | // Invariant: never empty | ||
190 | first_name: String, | ||
191 | middle_name: Option<String> | ||
192 | } | ||
193 | |||
194 | // Good | ||
195 | impl Person { | ||
196 | fn first_name(&self) -> &str { self.first_name.as_str() } | ||
197 | fn middle_name(&self) -> Option<&str> { self.middle_name.as_ref() } | ||
198 | } | ||
199 | |||
200 | // Not as good | ||
201 | impl Person { | ||
202 | fn first_name(&self) -> String { self.first_name.clone() } | ||
203 | fn middle_name(&self) -> &Option<String> { &self.middle_name } | ||
204 | } | ||
205 | ``` | ||
206 | |||
207 | |||
179 | # Premature Pessimization | 208 | # Premature Pessimization |
180 | 209 | ||
181 | Avoid writing code which is slower than it needs to be. | 210 | Avoid writing code which is slower than it needs to be. |