Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Dart comments


May 23, 2021 Dart Code style guide


Table of contents


Comments

Doc comments should be used when describing members and types.

Although Dart supports two types of doc annotations /// and /** we recommend /// it is more compact /** */ and two lines are empty). In some cases, /// easier to read, such as when a doc comment contains a list that uses * . . to mark individual list items.

// good
/// Parses a set of option strings.
///
/// For each option:
///
/// * If it is `null`, then it is ignored.
/// * If it is a string, then [validate] is called on it.
/// * If it is any other type, it is *not* validated.
void parse(List options) {
  // ...
}

In doc comments, you can use the markdown format.

You should use a single-line comment.

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

You can use block /* ... */

Comments should also be cased like normal sentences and punctuation should be added.

This is not to say that a comment should be a complete sentence, although in most cases it should be a complete sentence. The Number of Returned Entries is an acceptable comment.

// good
// Remove the last item from the collection.
// bad
// remove the last item from the collection

In comments, square brackets should be used to mark identifiers in the appropriate field.

If you put the name of a variable, method, or type in square brackets, the document generator can find the name and connect it to the code.

// good
import 'dart:math';

/// Rolls both [Dice] and returns the highest rolled value.
num greatestRoll(Dice a, Dice b) => max(a.roll(), b.roll());

//

The function signature should be described in the document comment.

In other languages, there are many labels and sections to explain what the parameters of the function are and what the return value is.

//bad
/// 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 IllegalArgumentException If there is already an option with
///     the given name or abbreviation.
Flag addFlag(String name, String abbr) {
  // ...
}

Dart is quite convenient, and you can integrate information such as parameters into the function description directly using square brackets.

// good
/// Defines a flag.
///
/// Throws an [IllegalArgumentException] 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) {
  // ...
}

Comments should be placed before metadata annotations.

// good
/// _Deprecated: Use [newMethod] instead._
@deprecated
oldMethod();
// bad
@deprecated
/// _Deprecated: Use [newMethod] instead._
oldMethod();