Contents

Effective Dart: Documentation

很容易就认为您的代码在今天显而易见,而没有意识到您对脑中已有上下文的依赖程度. 对您的代码不熟悉的人,甚至您健忘的未来自我也不会具有该上下文. 简洁,准确的评论仅需花费几秒钟即可编写,但可以节省其中一部分时间.

我们都知道代码应该是自我记录的,并不是所有注释都有用. 但是现实是,我们大多数人并未写出应有的评论. 这就像锻炼:从技术上讲,您可以做很多事情,但是您做得太少的可能性更大. 尝试加强它.

Comments

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

DO format comments like sentences.

// Not if there is nothing before it.
if (_chunks.isEmpty) return false;

大写第一个单词,除非它是区分大小写的标识符. 以句号结尾(我想应该是"!"或"?"). 所有注释都适用:文档注释,内联内容,甚至TODO. 即使是句子片段.

DON’T use block comments for documentation.

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

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

Doc comments

文档注释特别方便,因为dartdoc会对其进行解析并从中生成漂亮的文档页面 . doc注释是出现在声明之前且使用dartdoc查找的特殊///语法的任何注释.

DO use /// doc comments to document members and types.

短绒规则: slash_for_doc_comments

使用doc注释而不是常规注释使dartdoc可以找到它并为其生成文档.

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

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

如果您偶然发现仍然使用JavaDoc样式的代码,请考虑对其进行清理.

PREFER writing doc comments for public APIs.

Linter规则: package_api_docs, public_member_api_docs

您不必记录每个库,顶级变量,类型和成员,但是您应该记录其中的大多数.

CONSIDER writing a library-level doc comment.

与Java这样的语言不同,在Java中,类是程序组织的唯一单元,而在Dart中,库本身就是用户可以直接使用,导入和考虑的实体. 这使得library指令成为文档的好地方,该文档向读者介绍其中提供的主要概念和功能. 考虑包括:

  • 库用途的单句摘要.
  • 整个库中使用的术语说明.
  • 使用API​​的几个完整的代码示例.
  • 链接到最重要或最常用的类和函数.
  • 链接到与库有关的域上的外部引用.

您可以通过在文件开头的library指令上方放置doc注释来对library进行记录. 如果该库没有library指令,则可以添加一个指令只是将其文档注释挂起.

CONSIDER writing doc comments for private APIs.

Doc注释不仅针对图书馆公共API的外部使用者. 它们也有助于理解从库的其他部分调用的私有成员.

DO start doc comments with a single-sentence summary.

以简短的,以用户为中心的描述(以句点结尾)开始您的文档注释. 句子片段通常就足够了. 为读者提供足够的背景信息以使其适应自己的方向,并决定他们是否应该继续阅读或寻找其他解决方案.

/// Deletes the file at [path] from the file system.
void delete(String path) {
  ...
}
/// 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 separate the first sentence of a doc comment into its own paragraph.

在第一句之后添加一个空白行,以将其拆分为自己的段落. 如果多于一个解释的句子是有用的,请将其余内容放在后面的段落中.

这可以帮助您撰写简短的第一句话来总结文档. 同样,Dartdoc之类的工具在类和成员列表之类的地方,将第一段用作简短摘要.

/// 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) {
  ...
}
/// 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 redundancy with the surrounding context.

类文档注释的读者可以清楚地看到该类的名称,其实现的接口等.在为成员阅读文档时,签名就在其中,并且包含的​​类很明显. 无需在文档注释中说明所有内容. 相反,着眼于说明的读者知道的.

class RadioButtonWidget extends Widget {
  /// Sets the tooltip to [lines], which should have been word wrapped using
  /// the current font.
  void tooltip(List<String> lines) {
    ...
  }
}
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 starting function or method comments with third-person verbs.

文档注释应集中在代码的作用上 .

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

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

PREFER starting variable, getter, or setter comments with noun phrases.

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

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

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

避免在setter和getter上都带有文档注释,因为DartDoc将仅显示一个(getter上的一个).

PREFER starting library or type comments with noun phrases.

Doc comments for classes are often the most important documentation in your program. They describe the type’s invariants, establish the terminology it uses, and provide context to the other doc comments for the class’s members. A little extra effort here can make all of the other members simpler to document.

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

CONSIDER including code samples in doc comments.

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

人类擅长从示例中进行概括,因此即使是单个代码示例也使API易于学习.

DO use square brackets in doc comments to refer to in-scope identifiers.

Linter规则: comment_references

如果您将变量,方法或类型名称之类放在方括号中,则dartdoc会查找名称并链接到相关的API文档. 括号是可选的,但是当您引用方法或构造函数时,括号可以使其更清楚.

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

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

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

点语法也可以用来引用命名构造函数. 对于未命名的构造函数,在类名后加上括号:

/// To create a point, call [Point()] or use [Point.polar()] to ...

DO use prose to explain parameters, return values, and exceptions.

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

/// 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中的约定是将其集成到方法的描述中,并使用方括号突出显示参数.

/// 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 put doc comments before metadata annotations.

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

Markdown

您可以在文档注释中使用大多数markdown格式,而dartdoc将使用markdown包对其进行相应的处理.

已经有大量的指南向您介绍Markdown. 它的普遍流行是我们选择它的原因. 这只是一个简单的示例,可让您大致了解所支持的内容:

/// 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:
///
/// ```
/// 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 using markdown excessively.

如有疑问,请减少格式. 存在格式化功能来照亮您的内容,而不是替换它. 话语很重要.

AVOID using HTML for formatting.

在很少的情况下,例如表之类的情况下使用它可能会很有用,但是在几乎所有情况下,如果它太复杂而无法在Markdown中表达,那么最好不要表达它.

PREFER backtick fences for code blocks.

Markdown有两种指示代码块的方式:在每行的四个空格处缩进代码,或将其围绕在一对三引号"围栏"行中. 当在Markdown列表之类的东西中使用缩进已经有意义时,或者当代码块本身包含缩进的代码时,前一种语法就很脆弱.

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

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

Writing

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

本节列出了一些针对我们文档的准则. 通常,您可以从诸如技术写作风格之类的文章中了解有关技术写作最佳实践的更多信息.

PREFER brevity.

要清晰准确,但也要简洁.

AVOID abbreviations and acronyms unless they are obvious.

许多人不知道" ie"," eg"和" et al."是什么意思. 您确定该领域的每个人都知道的首字母缩写可能不会像您想象的那样广为人知.

PREFER using “this” instead of “the” to refer to a member’s instance.

在为类记录成员时,通常需要参考该成员被调用的对象. 使用" the"可能是模棱两可的.

class Box {
  /// The value this wraps.
  var _value;

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

by  ICOPY.SITE