当前位置:网站首页>Dart code comments and documentation specification
Dart code comments and documentation specification
2022-07-28 01:38:00 【Ma Nong @ official account on the island with the same name】
Preface
Good documentation is the key to successful code writing —— Although in today's rapid development , We don't like to write documents . But in fact, code documents can help us straighten out our thinking , Define the input and output parameters , It can also help us review the code in the future , Provide first-hand references for others on the team or code takers . such as ,Flutter The annotation of each component of is very good , in fact , Those comments directly generate Flutter Component instructions for . Of course , You can't write documents for the sake of writing documents , The code itself should be a good document , We should only write documents where needed , Instead of casually writing something meaningless . This article introduces Dart Code document writing specification officially recommended .
notes
stay Dart In the code , Comments refer to those supplementary instructions to the code that do not need to be included in the automatically generated document .
Annotation specifications 1: Use notes like sentences
Using sentences can maintain the integrity of the context of annotation meaning , It's like a phrase 、 Notes such as abbreviations may be understood differently by everyone .
// If the list element is empty , Then return directly false.
if (_itemList.isEmpty) return false;
Annotation specifications 2: Don't use block comments as documents
// The correct sample
void greet(String name) {
// Suppose we have a valid name .
print('Hi, $name');
}
// The wrong sample
void greet(String name) {
/* Suppose we have a valid name . */
print('Hi, $name!');
}
Can be used outside a code block /* ... */ Block annotation , But other parts of the code should use // notes .
Documentation Comments
Because it can pass through dartdoc Parse document comments and generate beautiful document pages , Make document comments particularly convenient .
Document annotation specification 1: Use /// Write documentation notes
stay Dart in , Unlike many other languages ,Dart Using three slashes /// As a document comment —— This is actually to make it easier to write comments , Compared with typing on the keyboard /** and */ In this way Java For document style document comments , Use /// Obviously faster ( No need to press shift Key switch ). meanwhile , For things like Markdown For such documents ,* It's actually a sign of a dot list .
// The correct sample
/// Gets the number of characters in the undivided previous block
int get length => ...
// The wrong sample
// Gets the number of characters in the undivided previous block
int get length => ...
Document annotation specification 2: For the public API Documentation should be prepared
public API It's open to the outside world , Writing documents helps to generate external API file , This allows the caller to understand these more clearly API The function of 、 Input/output parameter .
Document annotation specification 3: Write library level document comments
Dart In language , The annotation document of a library is the best way for users to understand the library , It is recommended to write the document of the library in the following way :
A brief summary informs the user of the purpose of the library . Introduce the terms used throughout the library . A complete set of using the library API Example code for . Link related important or common classes or methods . Provide access links for external references involved in the library .
for example , Here's from Flutter Excerpt from Animation<T> Class .
/// 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.
Document annotation specification 4: For private API Document
private API Although not open to the outside world , But the understanding of calling private members internally will be more helpful , Help us sort out the internal API Code .
Document annotation specification 5: Maintain a reasonable note paragraph structure
Usually , The first sentence of a code block should be used to name the purpose of the code block , Then start another paragraph for further description . This will allow the reader to understand the function of the code block at the first glance .
// The correct sample 1
/// Deletes the file at [path] from the file system.
void delete(String path) {
...
}
// The correct sample 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) {
...
}
// The wrong sample
/// 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) {
...
}
Document annotation specification 6: Don't repeat the introduction when the context is clear
Like... In the following error example radio button Just a lot more , The component itself has indicated that RadioButtonWidget 了 .
// The correct sample
class RadioButtonWidget extends Widget {
/// Sets the tooltip to [lines], which should have been word wrapped using
/// the current font.
void tooltip(List<String> lines) {
...
}
}
// The wrong sample
class RadioButtonWidget extends Widget {
/// Sets the tooltip for this radio button widget to the list of strings in
/// [lines].
void tooltip(List<String> lines) {
...
}
}
If you can't think of any comments to make on the code , Then I'd rather be empty than write meaningless notes , That will only delay the reader's time .
Document annotation specification 7: Provide sample code in the documentation
Yes demo Words , The caller will understand the code more quickly , Can save a lot of time , Greatly improve development efficiency .
/// Returns the lesser of two numbers.
///
/// ```dart
/// min(5, 3) == 3
/// ```
num min(num a, num b) => ...
Document annotation specification 8: Wrap the identifier in the file with square brackets
If square brackets are used, the variable 、 Method 、 After the type name is wrapped ,dartdoc Will find the same name , And link these names to the document . The parent attribute is optional , But the words provided will be more conducive to understanding .
/// 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()].
Document annotation specification 9: The parameters to be interpreted 、 Return values and exceptions are organized by language
Many programming languages use verbose tags and blocks to describe return values and parameters , but Dart This is not recommended , Instead, it is recommended to organize these elements in a natural language way , Make reading more smooth .
// The wrong sample
/// 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) => ...
// The correct sample
/// 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) => ...
Document annotation specification 10: Put the document annotation before the metadata annotation
// The correct sample
/// A button that can be flipped on and off.
@Component(selector: 'toggle')
class ToggleComponent {}
// The wrong sample
@Component(selector: 'toggle')
/// A button that can be flipped on and off.
class ToggleComponent {}
Markdown
stay Dart You can use... In your comment document Markdown grammar . So for the reading experience , have access to Markdown Syntax makes documents more hierarchical , Easier to read . however , Please don't show off your skills , overuse Markdown grammar . meanwhile , For code blocks , Recommended dart ... Block code form , The resulting code will be more readable .
More
This article introduces Dart Language code documentation and annotation specifications , In fact, the official websites are all English examples , Some content may not be suitable for Chinese . however , Suppose you want to write an open source plug-in library , Then you must use English , At this time, using the official document annotation style will make your plug-in more popular , For more information, please refer to the guidelines on the official website :Dart Document annotation guidelines .
I'm Manon on the island , Welcome to communicate with me in Zhihu Flutter Related issues .
边栏推荐
- 软件测试面试题:think_time的作用是什么?
- Cross domain requests in nodejs
- Leetcode 2347. the best poker hand
- 在一个字符串里面统计给定字符串的个数
- Anfulai embedded weekly report no. 275: 2022.07.18--2022.07.24
- 如何让数字零售承接起流量时代和留量时代的发展重任,或许才是关键所在
- How the test architects of bat factories interpret various disputes of the test platform
- 【样式集合1】tab 栏
- Three instance
- 迅为i.MX6ULL开发板Qt系统移植-交叉编译Qt代码
猜你喜欢
![[game] Nintendo Nintendo switch ultra detailed purchase / use guide and precautions (continuous update according to your own use...)](/img/7e/9e0e17e2ea8b8679ad7e1750a8b6d1.png)
[game] Nintendo Nintendo switch ultra detailed purchase / use guide and precautions (continuous update according to your own use...)

Software process that testers need to know

Shutter -- password login registration interface

Login function implementation

Develop plug-ins for the recording function of flutter

文章复现:超分辨率网络FSRCNN

Summary of common shortcut keys in idea

PHP利用某些函数bypass waf探讨

LeetCode 2341. 数组能形成多少数对

Oxygen temperature and humidity module
随机推荐
Principle of logistic regression
Learn how Baidu PaddlePaddle easydl realizes automatic animal recognition in aquarium
BYD semiconductor completed the a+ round financing of 800million yuan: 30 well-known investment institutions entered the market, with a valuation of 10.2 billion yuan!
BSP video tutorial issue 21: easy one key implementation of serial port DMA variable length transceiver, support bare metal and RTOS, including MDK and IAR, which is more convenient than stm32cubemx (
Meguiar sued liandian for secret theft and sentenced: liandian was fined NT $100million and three employees were sentenced!
伦敦银开盘时间知多少
Briefly understand namenode and datanode
在一个字符串里面统计给定字符串的个数
Thoroughly understand kubernetes scheduling framework and plug-ins
Lua进阶
站在数字零售转型的十字路口,我们需要用新的角度来看待它
软件测试面试题:如何发现数据库的相关问题?
Codeforces暑期训练周报(7.21~7.27)
S-RPN: Sampling-balanced region proposal network for small crop pest detection
Software test interview question: what are the performance test indicators?
Day 013 one dimensional array exercise
Flutter--密码登录注册界面
ICML2022 | 在线决策Transformer
还在用WIFI你就OUT了:LI-FI更牛!!!
Basic learning of cesium