2.1.6 名称与签名不够
06-名称与签名不够 — Comprehensive Rust
译文 · 基于 Comprehensive Rust
原文链接: https://google.github.io/comprehensive-rust/idiomatic/foundations-api-design/meaningful-doc-comments/what-isnt-docs.html
2.1.6 名称与签名不够
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
| // Copyright 2025 Google LLC
// SPDX-License-Identifier: Apache-2.0
// 不好
/// Returns a future that resolves when operation completes.
fn sync_to_server() -> Future<Bool>;
// 好
/// Sends local edits to the server, overwriting concurrent edits
/// if any happened.
fn sync_to_server() -> Future<Bool>;
// 不好
/// Returns an error if sending the email fails.
fn send(&self, email: Email) -> Result<(), Error>;
// 好
/// 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>;
|
动机:API 设计者可能过度相信“函数名与签名就够当文档”。
再次强调:名称与类型是文档的一部分。它们并不总是全部故事!
考虑名称、参数名或签名未覆盖的函数行为。
用注释消除歧义。细微行为、API 用户可能踩坑的行为,应当文档化。