跳到主要内容

Effective Dart: 文档

很容易认为今天的代码是显而易见的,而没有意识到你有多么依赖于你脑海中已有的上下文。不熟悉你的代码的人,甚至是你健忘的未来的自己,都不会有这种上下文。一条简洁、准确的注释只需要几秒钟的时间来编写,但可以为这些人节省数小时的时间。

我们都知道代码应该是自文档化的,并非所有注释都有帮助。但现实情况是,我们大多数人编写的注释都不如我们应该编写的那么多。这就像锻炼:从技术上讲,你可能做得太多,但更有可能的是你做得太少。尝试加强它。

注释

#

以下提示适用于您不希望包含在生成的文档中的注释。

DO 像句子一样格式化注释

#
dart
// Not if anything comes before it.
if (_chunks.isNotEmpty) return false;

首字母大写,除非它是区分大小写的标识符。以句点(或“!”或“?”结尾,我想)。这适用于所有注释:文档注释、内联内容,甚至 TODO。即使它只是一个句子片段。

DON'T 不要使用块注释进行文档编写

#
dart
void greet(String name) {
  // Assume we have a valid name.
  print('Hi, $name!');
}
dart
void greet(String name) {
  /* Assume we have a valid name. */
  print('Hi, $name!');
}

您可以使用块注释 (/* ... */) 临时注释掉一段代码,但所有其他注释都应使用 //

文档注释

#

文档注释尤其方便,因为 dart doc 会解析它们并从中生成美观的文档页面。文档注释是出现在声明之前并使用特殊的 /// 语法的任何注释,dart doc 会查找该语法。

DO 使用 /// 文档注释来记录成员和类型

#

Linter 规则: slash_for_doc_comments

使用文档注释而不是常规注释,使 dart doc 能够找到它并为其生成文档。

dart
/// The number of characters in this chunk when unsplit.
int get length => ...
dart
// The number of characters in this chunk when unsplit.
int get length => ...

由于历史原因,dart doc 支持文档注释的两种语法:///(“C# 风格”)和 /** ... */(“JavaDoc 风格”)。我们更喜欢 ///,因为它更紧凑。/***/ 为多行文档注释添加了两行无内容行。在某些情况下,/// 语法也更容易阅读,例如当文档注释包含使用 * 标记列表项的带项目符号的列表时。

如果您偶然发现仍在使用 JavaDoc 风格的代码,请考虑清理它。

PREFER 为公共 API 编写文档注释

#

Linter 规则: public_member_api_docs

您不必记录每个库、顶级变量、类型和成员,但您应该记录它们中的大多数。

CONSIDER 考虑编写库级别的文档注释

#

与 Java 等语言(类是程序组织的唯一单元)不同,在 Dart 中,库本身就是一个实体,用户可以直接使用、导入和思考。这使得 library 指令成为文档的绝佳位置,该文档向读者介绍库中提供的主要概念和功能。考虑包括

  • 库用途的单句摘要。
  • 整个库中使用的术语的解释。
  • 几个完整的代码示例,演示如何使用 API。
  • 指向最重要或最常用的类和函数的链接。
  • 指向库所关注领域外部参考的链接。

要记录库,请在 library 指令和可能附加在文件开头的任何注解之前放置文档注释。

dart
/// A really great test library.
@TestOn('browser')
library;

CONSIDER 考虑为私有 API 编写文档注释

#

文档注释不仅适用于库公共 API 的外部使用者。它们对于理解从库的其他部分调用的私有成员也很有帮助。

DO 用单句摘要开始文档注释

#

用简短的、以用户为中心的描述开始您的文档注释,并以句点结尾。句子片段通常就足够了。为读者提供足够的上下文,以便他们确定自己是否应该继续阅读或在其他地方寻找问题的解决方案。

dart
/// Deletes the file at [path] from the file system.
void delete(String path) {
  ...
}
dart
/// Depending on the state of the file system and the user's permissions,
/// certain operations may or may not be possible. If there is no file at
/// [path] or it can't be accessed, this function throws either [IOError]
/// or [PermissionError], respectively. Otherwise, this deletes the file.
void delete(String path) {
  ...
}

DO 将文档注释的第一句话分成单独的段落

#

在第一句话后添加一个空行,将其分成单独的段落。如果多于一句话的解释是有用的,请将其余部分放在后面的段落中。

这有助于您编写一个简洁的第一句话来概括文档。此外,像 dart doc 这样的工具使用第一段作为类和成员列表等位置的简短摘要。

dart
/// Deletes the file at [path].
///
/// Throws an [IOError] if the file could not be found. Throws a
/// [PermissionError] if the file is present but could not be deleted.
void delete(String path) {
  ...
}
dart
/// Deletes the file at [path]. Throws an [IOError] if the file could not
/// be found. Throws a [PermissionError] if the file is present but could
/// not be deleted.
void delete(String path) {
  ...
}

AVOID 避免与周围上下文的冗余

#

类的文档注释的读者可以清楚地看到类的名称、它实现的接口等等。在阅读成员的文档时,签名就在那里,并且封闭类是显而易见的。所有这些都不需要在文档注释中明确说明。相反,请专注于解释读者已经知道的内容。

dart
class RadioButtonWidget extends Widget {
  /// Sets the tooltip to [lines], which should have been word wrapped using
  /// the current font.
  void tooltip(List<String> lines) {
    ...
  }
}
dart
class RadioButtonWidget extends Widget {
  /// Sets the tooltip for this radio button widget to the list of strings in
  /// [lines].
  void tooltip(List<String> lines) {
    ...
  }
}

如果您真的没有什么有趣的话要说,而这些话又不能从声明本身推断出来,那么请省略文档注释。与其浪费读者的时间告诉他们他们已经知道的事情,不如什么都不说。

PREFER 用第三人称动词开始函数或方法注释

#

文档注释应侧重于代码做什么

dart
/// Returns `true` if every element satisfies the [predicate].
bool all(bool predicate(T element)) => ...

/// Starts the stopwatch if not already running.
void start() {
  ...
}

PREFER 用名词短语开始非布尔变量或属性注释

#

文档注释应强调属性是什么。即使对于可能进行计算或其他工作的 getter 也是如此。调用者关心的是该工作的结果,而不是工作本身。

dart
/// The current day of the week, where `0` is Sunday.
int weekday;

/// The number of checked buttons on the page.
int get checkedCount => ...

PREFER 用 "Whether" 后跟名词或动名词短语开始布尔变量或属性注释

#

文档注释应阐明此变量表示的状态。即使对于可能进行计算或其他工作的 getter 也是如此。调用者关心的是该工作的结果,而不是工作本身。

dart
/// Whether the modal is currently displayed to the user.
bool isVisible;

/// Whether the modal should confirm the user's intent on navigation.
bool get shouldConfirm => ...

/// Whether resizing the current browser window will also resize the modal.
bool get canResize => ...

DON'T 不要为属性的 getter 和 setter 都编写文档

#

如果属性同时具有 getter 和 setter,则仅为其中一个创建文档注释。dart doc 将 getter 和 setter 视为单个字段,如果 getter 和 setter 都有文档注释,则 dart doc 会丢弃 setter 的文档注释。

dart
/// The pH level of the water in the pool.
///
/// Ranges from 0-14, representing acidic to basic, with 7 being neutral.
int get phLevel => ...
set phLevel(int level) => ...
dart
/// The depth of the water in the pool, in meters.
int get waterDepth => ...

/// Updates the water depth to a total of [meters] in height.
set waterDepth(int meters) => ...

PREFER 用名词短语开始库或类型注释

#

类的文档注释通常是程序中最重要的文档。它们描述了类型的不变性,确立了它使用的术语,并为类成员的其他文档注释提供上下文。在这里稍加努力可以使所有其他成员的文档编写更简单。

dart
/// A chunk of non-breaking output text terminated by a hard or soft newline.
///
/// ...
class Chunk {
   ...
}

CONSIDER 考虑在文档注释中包含代码示例

#
dart
/// Returns the lesser of two numbers.
///
/// ```dart
/// min(5, 3) == 3
/// ```
num min(num a, num b) => ...

人类非常擅长从示例中进行概括,因此即使是单个代码示例也能使 API 更容易学习。

DO 在文档注释中使用方括号来引用作用域内的标识符

#

Linter 规则: comment_references

如果您将变量、方法或类型名称等内容放在方括号中,则 dart doc 会查找该名称并链接到相关的 API 文档。括号是可选的,但当您引用方法或构造函数时,可以使其更清晰。

dart
/// Throws a [StateError] if ...
/// similar to [anotherMethod()], but ...

要链接到特定类的成员,请使用类名和成员名,用点分隔

dart
/// Similar to [Duration.inDays], but handles fractional days.

点语法也可以用于引用命名构造函数。对于未命名的构造函数,在类名后使用 .new

dart
/// To create a point, call [Point.new] or use [Point.polar] to ...

DO 使用文字来解释参数、返回值和异常

#

其他语言使用冗长的标签和部分来描述方法的参数和返回值。

dart
/// Defines a flag with the given name and abbreviation.
///
/// @param name The name of the flag.
/// @param abbr The abbreviation for the flag.
/// @returns The new flag.
/// @throws ArgumentError If there is already an option with
///     the given name or abbreviation.
Flag addFlag(String name, String abbr) => ...

Dart 中的约定是将它集成到方法的描述中,并使用方括号突出显示参数。

dart
/// Defines a flag.
///
/// Throws an [ArgumentError] if there is already an option named [name] or
/// there is already an option using abbreviation [abbr]. Returns the new flag.
Flag addFlag(String name, String abbr) => ...

DO 将文档注释放在元数据注解之前

#
dart
/// A button that can be flipped on and off.
@Component(selector: 'toggle')
class ToggleComponent {}
dart
@Component(selector: 'toggle')
/// A button that can be flipped on and off.
class ToggleComponent {}

Markdown

#

您可以在文档注释中使用大多数 markdown 格式,dart doc 将使用 markdown 包相应地处理它。

已经有很多指南可以向您介绍 Markdown。它的普遍流行是我们选择它的原因。这只是一个快速示例,让您了解支持的内容

dart
/// This is a paragraph of regular text.
///
/// This sentence has *two* _emphasized_ words (italics) and **two**
/// __strong__ ones (bold).
///
/// A blank line creates a separate paragraph. It has some `inline code`
/// delimited using backticks.
///
/// * Unordered lists.
/// * Look like ASCII bullet lists.
/// * You can also use `-` or `+`.
///
/// 1. Numbered lists.
/// 2. Are, well, numbered.
/// 1. But the values don't matter.
///
///     * You can nest lists too.
///     * They must be indented at least 4 spaces.
///     * (Well, 5 including the space after `///`.)
///
/// Code blocks are fenced in triple backticks:
///
/// ```dart
/// this.code
///     .will
///     .retain(its, formatting);
/// ```
///
/// The code language (for syntax highlighting) defaults to Dart. You can
/// specify it by putting the name of the language after the opening backticks:
///
/// ```html
/// <h1>HTML is magical!</h1>
/// ```
///
/// Links can be:
///
/// * https://www.just-a-bare-url.com
/// * [with the URL inline](https://google.com)
/// * [or separated out][ref link]
///
/// [ref link]: https://google.com
///
/// # A Header
///
/// ## A subheader
///
/// ### A subsubheader
///
/// #### If you need this many levels of headers, you're doing it wrong

AVOID 过度使用 markdown

#

如有疑问,请减少格式化。格式化是为了阐明您的内容,而不是取代它。文字才是最重要的。

AVOID 避免使用 HTML 进行格式化

#

在极少数情况下,例如表格,可能可以使用它,但在几乎所有情况下,如果它太复杂而无法用 Markdown 表达,您最好不要表达它。

PREFER 使用反引号围栏来表示代码块

#

Markdown 有两种方式来指示代码块:在每行代码上缩进四个空格,或者将其包围在一对三反引号“围栏”行中。当在 Markdown 列表等内容中使用时,前一种语法是脆弱的,在这些列表中,缩进已经有意义,或者当代码块本身包含缩进代码时。

反引号语法避免了这些缩进问题,让您可以指示代码的语言,并且与对内联代码使用反引号一致。

dart
/// You can use [CodeBlockExample] like this:
///
/// ```dart
/// var example = CodeBlockExample();
/// print(example.isItGreat); // "Yes."
/// ```
dart
/// You can use [CodeBlockExample] like this:
///
///     var example = CodeBlockExample();
///     print(example.isItGreat); // "Yes."

写作

#

我们认为自己是程序员,但源文件中的大多数字符主要供人类阅读。英语是我们用来修改同事大脑的代码语言。至于任何编程语言,都值得努力提高您的熟练程度。

本节列出了一些关于我们文档的指南。您可以从 技术写作风格 等文章中了解更多关于技术写作最佳实践的信息。

PREFER 简洁

#

清晰、准确,但也简洁。

AVOID 避免使用缩写和首字母缩写词,除非它们很明显

#

很多人不知道 “i.e.”、“e.g.” 和 “et al.” 是什么意思。您确信您所在领域的所有人都知道的首字母缩写词可能并不像您想象的那么广为人知。

PREFER 使用 "this" 而不是 "the" 来指代成员的实例

#

在为类的成员编写文档时,您经常需要回指成员正在调用的对象。使用 “the” 可能会产生歧义。

dart
class Box {
  /// The value this wraps.
  Object? _value;

  /// True if this box contains a value.
  bool get hasValue => _value != null;
}