“This is the 17th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”
preface
Good documentation is the key to successful code writing — even though, in these days of rapid development, we don’t like documentation. But in practice, code documentation helps clarify our thinking, defines input and output parameters, and can also help us review the code later, providing a first-hand reference for the rest of the team or whoever is taking over the code. For example, the annotations for the components of Flutter are very good. In fact, those annotations directly generate the instructions for the components of Flutter. Of course, you can’t just write documentation for documentation’s sake, the code should be good documentation in itself, and you should only write documentation where you need it, not just random stuff that doesn’t make sense. This article introduces the Dart official recommended code documentation specification.
annotation
In Dart code, comments are additions to the code that do not need to be included in the auto-generated documentation.
Comment specification 1: Use comments like sentences
Using sentences preserves the contextual integrity of the meaning of a comment, while comments such as phrases and abbreviations may differ from person to person.
// If the list element is empty, return false.
if (_itemList.isEmpty) return false;
Copy the code
Comment specification 2: Do not use block comments as documentation
// Correct example
void greet(String name) {
// Suppose we have a valid name.
print('Hi, $name');
}
// Error example
void greet(String name) {
/* Assume we have a valid name. * /
print('Hi, $name! ');
}
Copy the code
You can use /*… outside of a code block. */ block comments, but // comments should be used elsewhere in the code.
Documentation comments
Document annotations are especially convenient because they can be parsed through DartDoc to produce nice document pages.
Document comment specification 1: Write document comments using ///
Dart differs from many other languages in that it uses three slashes /// for document comments — this makes it easier to write comments than typing /** and */ on the keyboard in Java document style. Using /// is obviously faster (no need to press shift to switch). Also, for a document like Markdown, the * is a list of dots.
// Correct example
/// Gets the number of characters in the unsplit previous block
int get length => ...
// Error example
// Get the number of characters in the unsplit block
int get length => ...
Copy the code
Documentation annotation specification 2: You should document public apis
Public apis are open to the public, and writing documentation helps to generate external API documentation so that callers have a clearer understanding of the functions, input and output parameters of these apis.
Document annotation specification 3: Write document annotations at the library level
In Dart, a library’s comment documentation is the best way for users to learn about the library. It is recommended to write library documentation as follows:
- A short summary informs the user of the library’s purpose.
- Describes the terminology used throughout the library.
- A complete set of sample code that uses the library API.
- Link related important or generic classes or methods.
- Provides access links to external references involved in the library.
For example, here is a comment from the Animation
class from Flutter.
/// An animation with a value of type `T`.
///
/// An animation consists of a value (of type `T`) together with a status. The
/// status indicates whether the animation is conceptually running from
/// beginning to end or from the end back to the beginning, although the actual
/// value of the animation might not change monotonically (e.g., if the
/// animation uses a curve that bounces).
///
/// Animations also let other objects listen for changes to either their value
/// or their status. These callbacks are called during the "animation" phase of
/// the pipeline, just prior to rebuilding widgets.
///
/// To create a new animation that you can run forward and backward, consider
/// using [AnimationController].
///
/// See also:
///
/// * [Tween], which can be used to create [Animation] subclasses that
/// convert `Animation<double>`s into other kinds of `Animation`s.
Copy the code
Document annotation specification 4: Document private apis
Private apis are not open to the public, but it is helpful to understand how to call private members internally and to comb through the internal API code.
Document comment specification 5: Maintain a reasonable comment paragraph structure
In general, you should name the purpose of a code block in the first sentence, followed by a further description in a separate paragraph. This gives the reader a first glance at the functionality of the code block.
// Correct example 1
/// Deletes the file at [path] from the file system.
void delete(String path) {
...
}
// Correct example 2
/// 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) {
...
}
// Error example
/// 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) {
...
}
Copy the code
Documentation Note Specification 6: Do not repeat the introduction if the context is clear
The radio Button in the following error example is redundant, and the component itself already identifies the RadioButtonWidget.
// Correct example
class RadioButtonWidget extends Widget {
/// Sets the tooltip to [lines], which should have been word wrapped using
/// the current font.
void tooltip(List<String> lines) { ... }}// Error example
class RadioButtonWidget extends Widget {
/// Sets the tooltip for this radio button widget to the list of strings in
/// [lines].
void tooltip(List<String> lines) { ... }}Copy the code
If you can’t think of anything to comment on your code, leave it blank rather than write unnecessary comments, which will only delay the reader’s time.
Documentation comments Specification 7: Provide sample code in documentation
With demo, callers will understand the code more quickly, saving a lot of time and greatly improving development efficiency.
/// Returns the lesser of two numbers.
///
/// ```dart
/// min(5, 3) == 3
/// ` ` `
num min(num a, num b) => ...
Copy the code
Document Comment Specification 8: Wrap identifiers within files with square brackets
If the variable, method, and type names are wrapped in square brackets, DartDoc looks for the same names and links them into the document. The parent attribute is optional, but is easier to understand if provided.
/// Throws a [StateError] if ...
/// similar to [anotherMethod()], but ...
/// Similar to [Duration.inDays], but handles fractional days.
/// To create a point from polar coordinates, use [Point.polar()].
Copy the code
Documentation comments Specification 9: Organize the parameters, return values, and exceptions that need to be interpreted by language
Many programming languages use lengthy tags and blocks to describe return values and parameters, but Dart does not recommend this. Instead, it recommends organizing these elements in natural language to make reading easier.
// Error example
/// 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) => ...
// Correct example
/// 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) => ...
Copy the code
Document annotation specification 10: Place document annotations before metadata annotations
// Correct example
/// A button that can be flipped on and off.
@Component(selector: 'toggle')
class ToggleComponent {}
// Error example
@Component(selector: 'toggle')
/// A button that can be flipped on and off.
class ToggleComponent {}
Copy the code
Markdown
Markdown syntax can be used in Dart’s comment documentation. So for the reading experience, you can use Markdown syntax to make the document more hierarchical and easier to read. However, please don’t show off and overuse Markdown syntax. In the meantime, dart is recommended for code blocks… Block code, so the resulting code is more readable.
More content
This article introduces the code documentation and comment specification for the Dart language. In fact, the official website contains examples in English, some of which may not be suitable for Chinese. However, if you want to write an open source plugin library, you will need to use English, and using the official documentation style will make your plugin more popular. For more information, see the Dart Documentation Guide.
I am dao Code Farmer with the same name as my wechat official account. This is a column about the introduction and practice of Flutter, providing systematic learning articles about Flutter. See the corresponding source code here: The source code of Flutter Introduction and Practical column. If you have any questions, please add me to the wechat account: island-coder.
👍🏻 : feel the harvest please point a praise to encourage!
🌟 : Collect articles, easy to look back!
💬 : Comment exchange, mutual progress!