Version: 1.0.2
Last Updated: October 15, 2024
This CEP (Coding Enhancement Proposal) outlines the documentation style guidelines for the project. The goal is to establish consistent and clear documentation practices across various programming languages used within the project, including Python, Java, Objective-C, Shell scripts, and more. By adhering to these guidelines, we aim to improve code readability, maintainability, and ease of understanding for all contributors.
Scope:
- Python Docstrings
- Java Documentation (Javadoc)
- C, C++, Objective-C, Swift, and Similar Documentation (DocC)
- Doxygen/HeaderDoc Documentation
- Shell Scripts (
#
comments) - XML-style Comments (
<!-- -->
)
Goals:
- Define standardized documentation practices for each language and context.
- Clarify ambiguous terms and usage within documentation.
- Provide guidelines on tooling and automation for documentation generation and linting.
- Encourage consistency and clarity in all forms of code documentation.
- Definitions
- General Principles
- Python Documentation Style
- Java Documentation Style
- C, C++, Objective-C, Swift, and Similar Documentation Style (DocC)
- Doxygen/HeaderDoc Documentation Style
- Shell Scripts Documentation Style
- XML-style Comments Documentation Style
- Tooling and Automation
- Conclusion
This section defines terms that may have ambiguous meanings in different contexts. Establishing clear definitions ensures consistency across documentation and code within the project.
Note: The keywords MUST, SHALL, SHOULD, MAY, and OPTIONAL in this document are to be interpreted as described in RFC 2119.
A standalone block of code, typically non-member, non-object-oriented, or global, that performs a specific task and can be reused throughout the program.
- Usage in Documentation: Used in procedural or functional programming paradigms. In documentation, refer to standalone blocks of code as functions.
A function that is associated with a class or an object. Methods operate on data contained within an instance of a class.
- Usage in Documentation: In object-oriented programming languages like Java, C++, Swift, Objective-C, etc., functions that are part of classes or similar OOP structures are referred to as methods. Documentation MUST consistently distinguish between functions and methods.
Short for "macro instruction," a macro is a rule or pattern that specifies how input sequences are mapped to replacement output sequences, often used for code expansion or simplification.
- Usage in Documentation: Documentation MUST consistently differentiate between macros, pragmas, and directives. In languages like C and C++, macros are defined using
#define
.
An instruction to the compiler or interpreter that controls how it processes the source code.
-
Usage in Documentation (Python): Refers to a tool's directive (e.g., flake8, pylint, coverage). Applies to configurations or instructions provided to these tools. Documentation SHOULD clarify the context when referring to directives associated with tools.
-
Usage in Documentation (C/C++/Objective-C): Refers to linter, compiler, or preprocessor directives such as
#include
and#ifdef
. Documentation SHOULD follow the usage of the term directive as per C's documentation and differentiate it from macros.
A special-purpose directive used to provide additional information to the compiler.
-
Usage in Documentation (C/C++/Objective-C): Refers specifically to
#pragma
directives. Use the term pragma only in this context. -
Usage in Documentation (Python): Only when appropriate to refer to encoding declarations and is considered an anti-pattern in documentation outside the official Python Foundation's documentation. Tools SHOULD recommend removing from documentation or replacing with directive instead.
A program written for an interpreter, distinguishing it from the file that contains the script and the process instance when executed by the relevant interpreter.
- Usage in Documentation: Applies to shell scripts, Python scripts, Lua scripts, JavaScript, etc. Use script to refer to code intended to be run by an interpreter.
A program, command, or script that is invoked, either by automation or by a user, to help accomplish a task.
- Usage in Documentation: Refers to software utilities or applications that aid in development, testing, deployment, or other tasks.
A reusable piece of software containing code, data, or resources.
- Usage in Documentation:
- Python: Refers to a Python module, which is a single Python file or a collection of files organized as a package.
- C/C++/Objective-C: Refers to a library or framework with a Clang-style module file. Refer to Clang Modules for details.
- GitHub Actions (GHA): May refer to a Python module or an NPM package.
- Java: Considered an anti-pattern; recommend using package or archive instead.
- Shell/Bash: May refer to git submodules or context-specific meanings.
- Others: Unless matching previous uses, avoid the term in favor of package or component.
A deliverable in a form that would be passed to a package manager, representing a collection of software components.
- Usage in Documentation: Refers to a software package intended for distribution and installation.
An input value passed to a function, method, or tool.
- Usage in Documentation:
- Functions/Methods: Used to pass inputs to functions or methods.
- CLI Tools: Non-flag inputs provided at the time of invoking the tool (i.e., not piped input).
Variables listed as part of a method's definition; they receive the values of the arguments when the function is called.
-
Usage in Documentation: Refers to method inputs, emphasizing the distinction from arguments.
-
Usage in Documentation (Tools): Refers to members of sets of arguments, settings, or configurations supplied to tools, emphasizing that the manner of input is insignificant compared to the fact that the setting or flag value is provided.
A command-line argument that modifies the operation of a tool, typically prefixed with one or two dashes (e.g., -v
or --verbose
).
- Usage in Documentation: Refers to dash-style arguments for tools; may occasionally refer to on/off type settings.
A storage location identified by a name that holds data which can be modified during program execution.
- Usage in Documentation: Can be local, a field, or a constant (though constants are technically immutable). The term variable is acceptable but may be vague.
A variable associated with an instance of a class, typically with restricted access (e.g., private or protected).
- Usage in Documentation: Field does not imply the presence of getter and setter methods. In object-oriented languages, fields represent the state of an object.
A characteristic or property of an object.
- Usage in Documentation: The term attribute can be vague and is easily confused. In Python and other languages where it has a technical meaning, it may be used accordingly. Otherwise, consider avoiding it to prevent ambiguity.
A special kind of class member that provides controlled access to an attribute, typically through getter and setter methods.
-
Usage in Documentation: Properties encapsulate instance variables, allowing for validation or computation when values are accessed or modified.
-
Note for Java: Refer to Difference between Field, Variable, Attribute, and Property in Java for language-specific distinctions.
The data held by a variable or returned by an expression.
- Usage in Documentation:
- Typeless Languages: Use value when discussing types, e.g., "string value" or "int value."
- Typed Languages: Refers to the actual data of a specified type.
A classification that specifies the kind of data that can be stored and the operations that can be performed on it.
- Usage in Documentation: Defines the nature of variables and expressions (e.g.,
int
,string
,float
).
A blueprint or template from which objects are created, encapsulating data for the object and methods to manipulate that data.
- Usage in Documentation: Use language-specific or general object-oriented programming (OOP) definitions.
An instance of a class containing data and methods.
-
Usage in Documentation: Refers to an OOP object.
-
Exception in Java: Since
Object
is the root class, avoid using object for other meanings. -
Exception in Objective-C: Similar to Java; avoid using object for other meanings. Tools may recommend terms like thing or entity.
-
Non-OOP Languages: Prefer structure or other relevant terms instead of object.
An event that occurs during the execution of a program that disrupts the normal flow of instructions, typically due to an error.
- Usage in Documentation: Exceptions can be caught and handled. In languages that distinguish between exceptions and errors, use exception for catchable anomalies.
A serious issue that may not be caught or handled, often indicating critical problems.
- Usage in Documentation: Errors typically cannot be caught and may lead to program termination. Be cautious in documentation; if an error is catchable, it should be considered an exception and documented accordingly, even if named as an "Error."
Metadata added to source code that provides information to compilers or tools.
-
Usage in Documentation: Follow language conventions. For example, in Java, annotations like
@Override
provide instructions to the compiler. -
Note: If no relevant convention exists, avoid using annotation in documentation.
A design pattern that allows additional behavior to be added to a function or method dynamically.
-
Usage in Documentation (Python): A function that modifies the behavior of another function or method. Refer to PEP 318 for details.
-
Note: Use the Python-specific meaning when referring to decorators.
A special string literal used to document a specific segment of code.
- Usage:
- Python: A string literal occurring as the first statement in a module, function, class, or method definition. See PEP 257.
- DocC: Any
///
style comment used in languages or tools that support DocC. - Other Languages: Avoid using docstring in documentation outside of these contexts.
A programmer-readable annotation in the source code that is ignored by compilers and interpreters.
- Usage:
- Refers to the content within source code comments.
- In GitHub Actions (GHA), may also refer to annotations in pull requests or merge requests.
- Exception in GitHub Issues/PRs: May refer to user-generated comments in discussions.
Non-code text that explains aspects of a project, code, or other topics to aid understanding.
- Usage:
- Includes manuals, READMEs, docstrings, Javadoc code comments, shell script comment lines (excluding inline comments), and other explanatory materials.
- Note: This convention does not consider all code comments in all contexts to be documentation. Inline comments within code are generally excluded from this definition.
A collection of precompiled routines that programs can use.
- Usage in Documentation:
- C-type Languages: Refers to compiled code (static or dynamic libraries) linked to programs.
- Python: Refers to external modules or packages imported into a program.
Characters or sequences of characters that represent horizontal or vertical space in text.
- Usage: Includes space, tab, newline, and other non-printable spacing characters.
The following table enumerates the Unicode whitespace characters along with their code points, HTML encoding, LaTeX equivalents, and shell escape forms:
Code Point | Name | HTML Encoding | LaTeX Equivalent | Shell Escape Form |
---|---|---|---|---|
U+0009 | CHARACTER TABULATION | 	 |
\hspace{1em} (approximate) |
$'\t' |
U+000A | LINE FEED (LF) | 
 |
N/A | $'\n' |
U+000B | LINE TABULATION |  |
N/A | $'\v' |
U+000C | FORM FEED (FF) |  |
N/A | $'\f' |
U+000D | CARRIAGE RETURN (CR) | 
 |
N/A | $'\r' |
U+0020 | SPACE |   |
(space character) | (space character) |
U+0085 | NEXT LINE (NEL) | … |
N/A | $'\u0085' |
U+00A0 | NO-BREAK SPACE |   , |
~ (non-breaking space) |
$'\u00A0' |
U+1680 | OGHAM SPACE MARK |   |
N/A | $'\u1680' |
U+180E | MONGOLIAN VOWEL SEPARATOR | ᠎ |
N/A | $'\u180E' |
U+2000 | EN QUAD |   |
\enskip |
$'\u2000' |
U+2001 | EM QUAD |   |
\quad |
$'\u2001' |
U+2002 | EN SPACE |   ,   |
\enspace |
$'\u2002' |
U+2003 | EM SPACE |   ,   |
\quad |
$'\u2003' |
U+2004 | THREE-PER-EM SPACE |   |
\hspace{0.3333em} |
$'\u2004' |
U+2005 | FOUR-PER-EM SPACE |   |
\hspace{0.25em} |
$'\u2005' |
U+2006 | SIX-PER-EM SPACE |   |
\hspace{0.1667em} |
$'\u2006' |
U+2007 | FIGURE SPACE |   |
\hphantom{0} (approximate) |
$'\u2007' |
U+2008 | PUNCTUATION SPACE |   |
\hspace{0.1667em} (approximate) |
$'\u2008' |
U+2009 | THIN SPACE |   ,   |
\, |
$'\u2009' |
U+200A | HAIR SPACE |   |
\hspace{0.0833em} |
$'\u200A' |
U+2028 | LINE SEPARATOR | 
 |
N/A | $'\u2028' |
U+2029 | PARAGRAPH SEPARATOR | 
 |
N/A | $'\u2029' |
U+202F | NARROW NO-BREAK SPACE |   |
\nobreak\hspace{0.1667em} |
$'\u202F' |
U+205F | MEDIUM MATHEMATICAL SPACE |   |
\: |
$'\u205F' |
U+3000 | IDEOGRAPHIC SPACE |   |
\hspace{1em} (approximate) |
$'\u3000' |
Notes:
-
LaTeX Equivalents:
- Not all Unicode whitespace characters have direct LaTeX equivalents. Approximate representations are provided where possible.
- The
~
in LaTeX represents a non-breaking space corresponding to U+00A0. \quad
and\qquad
provide spaces of one and two ems, respectively.- Thin spaces in LaTeX are represented by
\,
and medium spaces by\:
. \enskip
provides a space of half an em.
-
Shell Escape Forms:
- Uses the
$'...'\
syntax to represent Unicode characters with\uXXXX
. - Standard ASCII control characters use escape sequences like
\t
,\n
, etc.
- Uses the
- Consistency: Documentation MUST maintain a consistent style throughout the codebase.
- Clarity: Write clear and concise descriptions, avoiding ambiguity.
- Standardization: Use the defined terms and structures within this CEP to ensure uniformity across all documentation.
- Tool Integration: Where possible, documentation SHOULD be compatible with automated tools for generation and linting.
There are two primary sources for building documentation:
- Explanatory Documents: Standalone documents that provide detailed explanations (see Definition: Documentation).
- Docstrings: Extractable documentation within the code itself (see Definition: Docstring).
The following foundational documents and style guides form the basis of our Python documentation style:
-
PEP 8: Follow PEP 8 as it applies to documentation, except where CEP-7 supersedes or modifies it. CEP-7 compliant style SHOULD be compatible with PEP-8 but SUPERCEDES PEP-8 on specific points detailed below.
-
PEP 257: Follow PEP 257 for docstring conventions, except where CEP-7 supersedes or modifies it.
-
PEP 256 and PEP 258: Align with PEP 256 and PEP 258 where applicable, except where CEP-7 supersedes or modifies them.
-
PEP 3120: Adhere to PEP 3120 regarding UTF-8 default source encoding.
Note: The Google Markdown Style Guide provides valuable insights and can be considered a supplementary reference as needed.
-
Rule: Docstrings SHOULD be multi-lined in most cases, even for short descriptions. This enhances readability and provides space for additional information.
-
Interaction with PEP-8 and PEP-257: While PEP-8 and PEP-257 allow single-line docstrings for simple functions, CEP-7 PREFERS multi-line docstrings to maintain consistency.
Python docstrings MUST follow the style outlined below, inspired by our conventions. The docstring consists of several parts:
-
Rule: Begin with a concise, one-line abstract of the module, class, method, or function's purpose. This abstract SHOULD be descriptive and start with a verb in the imperative mood.
-
Interaction with PEP-257: PEP-257 recommends that the summary line be a short phrase ending with a period. CEP-7 SUPERCEDES this by requiring an imperative tone.
👍 GOOD
"""
Initialize the database connection.
"""
🙅 BAD
"""
This function initializes the database connection.
"""
- Rule: Provide additional details if necessary, following the summary line after a blank line.
- Rule: Use appropriate headings and labels to distinguish between Arguments, Fields, and Parameters as per the definitions.
Example:
"""
Initialize the database connection.
Arguments:
host (str): The database host.
port (int): The port number.
Returns:
Connection: The database connection object.
"""
- Rule: Describe the return value of the function or method under the Returns heading.
- Rule: List any exceptions that the function or method can raise under the Raises heading.
- Rule: Place doctests at the very end of the docstring. The testing heading SHOULD be replaced with a specific heading such as "Testing", "Minimal Acceptance Testing", "Meta-Testing", or "Unit-Testing".
Example:
"""
Initialize the database connection.
Arguments:
host (str): The database host.
port (int): The port number.
Returns:
Connection: The database connection object.
Unit-Testing:
Testcase 1: Successful connection.
>>> conn = initialize_connection('localhost', 5432)
>>> assert conn is not None
Testcase 2: Invalid port number.
>>> initialize_connection('localhost', -1)
Traceback (most recent call last):
...
ValueError: Invalid port number.
"""
- Rule: Use consistent headings to separate sections, matching the terms defined in the Definitions section.
-
Rule: Strive for clear and concise documentation. MUST avoid ambiguity by using precise language and the recommended keywords from the Definitions section.
-
Interaction with PEP-8 and PEP-257: CEP-7 places a stronger emphasis on clarity and precision, superseding PEP-8 and PEP-257 where necessary.
-
Installation:
pip install flake8 flake8-docstrings flake8-bugbear darglint
-
Configuration:
In
setup.cfg
or.flake8
:[flake8] select = C,E,F,W,B,B950 ignore = D203 # 1 blank line required before class docstring D212 # Multi-line docstring summary should start at the first line docstring-convention = google docstring_style = google
- Note: The
max-line-length
configuration is omitted to remain consistent with the project's threshold.
- Note: The
-
Extensions:
In
conf.py
, configure Sphinx with the following extensions:extensions = [ 'sphinx.ext.napoleon', 'autodoc2', 'sphinx.ext.autosummary', 'sphinx.ext.githubpages', 'myst_parser', 'sphinx.ext.doctest', 'sphinx.ext.todo', 'sphinx.ext.linkcode', 'sphinx.ext.viewcode' ]
-
Napoleon Settings:
napoleon_google_docstring = True napoleon_numpy_docstring = False napoleon_include_private_with_doc = False napoleon_include_special_with_doc = False
-
Interaction with CEP-7:
- The configuration aligns Sphinx with CEP-7's docstring style, ensuring proper parsing and rendering of the documentation.
- Rule: Ensure UTF-8 encoding is used consistently throughout the codebase, adhering to PEP 3120.
Additional Considerations
-
Consistency
- Rule: Maintain a consistent documentation style across all modules and packages.
-
Tool Compatibility
- Note: Be aware that CEP-7 style may be incompatible with certain tools like Black due to its inflexibility. Consider alternative tools or configurations.
Java utilizes Javadoc comments for documentation. This section details the conventions for writing Javadoc comments in compliance with CEP-7.
- Javadoc Guide: Link to Javadoc Guide.
-
Imperative Abstracts:
- Begin with an abstract in the imperative tone.
- Provide a concise summary of the method's purpose.
-
Structure:
- Use standard Javadoc tags:
@param
,@return
,@throws
. - Include full signatures when referencing methods or classes.
- Use standard Javadoc tags:
-
Example:
/** * Compute the factorial of a number. * * @param number The non-negative integer whose factorial is to be computed. * @return The factorial of the provided number. * @throws IllegalArgumentException If the number is negative. */ public int factorial(int number) throws IllegalArgumentException { // Implementation }
-
Formatting and Tags:
- Use
<p>
for paragraphs. - Use code samples within
<pre><code>...</code></pre>
.
- Use
-
Clarity:
- Ensure descriptions are clear and concise.
- Avoid redundancy.
-
Tooling:
- Checkstyle: Configure to enforce Javadoc conventions.
- Javadoc Tool: Use for generating documentation.
This section outlines the conventions and guidelines for documenting code in languages like C, C++, Objective-C, Swift, and others that utilize DocC and C-style //
comments. The goal is to ensure consistency and clarity across all documentation within the project.
Note: The keywords MUST, SHOULD, MAY, and RECOMMENDED in this document are to be interpreted as described in RFC 2119.
DocC is a documentation compiler that generates documentation from source code comments, primarily used in Swift and Objective-C projects. It uses a combination of C-style ///
comments and Markdown to create rich documentation.
The following foundational documents and style guides form the basis of our documentation style:
- DocC Documentation:
- Modified Markdown for DocC:
- C Standards:
- While C11, C17, and C23 standards define comment syntax, they do not specify documentation conventions. Our style aligns with DocC practices where applicable.
- Consistency: Documentation MUST maintain a consistent style throughout the codebase.
- Clarity: Write clear and concise descriptions. SHOULD avoid ambiguity.
- Alignment: Comments MUST be indented to align with the code they describe.
- Single-Line Documentation:
- Use
///
for single-line documentation comments. - These comments MUST appear immediately before the declaration they document.
- Indentation: Align with the code indentation level.
- Trailing and Leading Spaces: SHOULD NOT have unnecessary trailing or leading spaces.
- Use
Example:
/// Initializes a new instance of the class.
- (instancetype)init {
// Implementation
}
- Multi-Line Documentation:
- For longer descriptions, use consecutive
///
lines. - Alternatively, use
/** ... */
comment blocks starting with/**
and ending with*/
.
- For longer descriptions, use consecutive
Example with ///
:
/// Initializes a new instance with the specified parameters.
///
/// - Parameters:
/// - name: The name of the item.
/// - value: The value associated with the item.
///
/// - Returns: An initialized instance of the class.
- (instancetype)initWithName:(NSString *)name value:(NSInteger)value {
// Implementation
}
Example with /** ... */
:
/**
Initializes a new instance with the specified parameters.
- Parameters:
- name: The name of the item.
- value: The value associated with the item.
- Returns: An initialized instance of the class.
*/
- (instancetype)initWithName:(NSString *)name value:(NSInteger)value {
// Implementation
}
- Indentation:
- Documentation comments MUST be indented to match the code block they refer to.
- Trailing and Leading Spaces:
- Trailing and leading spaces in comments SHOULD NOT be present.
- Line Length:
-
Documentation lines SHOULD not exceed 100 characters to enhance readability.
-
Configuring DocC Line Length:
-
To configure DocC to accept the new max line length of 100, you can adjust the line length setting in your code style tools such as ClangFormat.
-
Example:
# .clang-format ColumnLimit: 100
-
-
- Markdown Syntax:
- DocC supports a subset of Markdown for formatting.
- Use Markdown syntax for emphasis, lists, code snippets, and links.
Example with Lists:
/// This method performs the following steps:
/// 1. Validates the input.
/// 2. Processes the data.
/// 3. Returns the result.
- (void)performTask {
// Implementation
}
Example with Code Snippets:
/// Example:
/// ```objective-c
/// ResultType *result = [self performTask];
/// ```
- (ResultType *)performTask {
// Implementation
}
- Use the recommended keywords from the Definitions section to reduce ambiguity.
- Macro, Directive, and Pragma:
- Use these terms appropriately in documentation.
- Ensure clarity by following the definitions provided in CEP-7.
- Inline Comments:
- Use
/* ... */
for inline comments that are not processed by DocC. - Suitable for temporary notes or code explanations within method implementations.
- Use
- Avoid for Documentation:
/* ... */
comments SHOULD NOT be used for documentation intended for DocC processing.
- DocC Keywords:
- Utilize DocC-specific keywords and annotations, such as
- Parameters:
,- Returns:
, and- Throws:
.
- Utilize DocC-specific keywords and annotations, such as
- Comparison with Pure Markdown:
- While DocC extends Markdown, when documentation is intended for pure Markdown processing, ensure that syntax remains compatible.
Example with DocC Tags:
/// Adds two numbers and returns the result.
///
/// - Parameters:
/// - a: The first number.
/// - b: The second number.
///
/// - Returns: The sum of `a` and `b`.
- (NSInteger)addNumber:(NSInteger)a toNumber:(NSInteger)b {
return a + b;
}
- Sections:
- Use special sections like
- Note:
,- Warning:
, and- Important:
to highlight critical information.
- Use special sections like
Example:
/// Calculates the factorial of a number.
///
/// - Parameter n: The number to calculate the factorial of.
/// - Returns: The factorial of `n`.
///
/// - Warning: The input must be a non-negative integer.
- (NSInteger)factorialOfNumber:(NSInteger)n {
// Implementation
}
- Excluding from Documentation:
- Use
:nodoc:
to exclude certain declarations from generated documentation.
- Use
- Overloaded Methods:
- Ensure each overloaded method has its own documentation comment.
- Generics and Protocols:
- Document generic parameters and protocol conformances clearly.
-
Accessibility Outside DocC Tools:
- Ensure that documentation remains accessible and understandable even outside DocC tools when possible.
-
Consistent Use of
///
Comments:- Use
///
style comments consistently for DocC processing.
- Use
-
Alignment with Code:
- Ensure that comments are properly indented, aligning with the code they describe.
-
Effective Use of Markdown:
- Utilize Markdown syntax for formatting within comments, including lists and code snippets.
-
Clear and Concise Descriptions:
- Provide clear explanations of functions, methods, and parameters in the documentation.
-
Use of Special Sections:
- Use sections like
- Note:
,- Warning:
, and- Important:
to highlight important information.
- Use sections like
This section outlines the conventions and guidelines for documenting code using Doxygen or HeaderDoc styles, ensuring consistency and clarity across all documentation within the project.
- Doxygen: Refer to the Doxygen Manual for standard conventions applicable to languages like C++, C, Java, Objective-C, and more.
- HeaderDoc: Refer to the HeaderDoc User Guide for conventions specific to C, C++, and Objective-C.
- Consistency: Maintain a consistent documentation style throughout the codebase.
- Clarity: Write clear and concise descriptions, avoiding ambiguity.
- Applicability: Use Doxygen/HeaderDoc styles in projects where automated documentation generation is desired.
- Comment Blocks:
- Doxygen: Use
/** ... */
or/*! ... */
for comment blocks. - HeaderDoc: Use
/*! ... */
for comment blocks.
- Doxygen: Use
- Placement: Place comment blocks immediately before the entity they document (e.g., functions, classes, variables).
- Brief Description:
- Start with a brief, one-line summary of the entity's purpose.
- Use an imperative tone for clarity.
- Detailed Description:
- Provide additional details in subsequent paragraphs if necessary.
- Parameters and Return Values:
- Use appropriate tags to document parameters, return values, and exceptions.
- Doxygen:
@param
or\param
to describe parameters.@return
or\return
to describe return values.@throws
or\throws
to describe exceptions.
- HeaderDoc:
@param
to describe parameters.@return
to describe return values.@throws
to describe exceptions.
- Tags and Commands: Use standard tags and commands as specified in the Doxygen/HeaderDoc manuals.
- Special Sections: Use headings like
@note
,@warning
, and@attention
to highlight important information.
Doxygen Example:
/*!
* Initialize the system components.
*
* Sets up necessary configurations and allocates resources required for operation.
*
* @param config The configuration settings.
* @return `true` if initialization was successful; `false` otherwise.
* @note Must be called before any other system functions.
*/
bool initializeSystem(const Config& config);
HeaderDoc Example:
/*!
* @function processData
* @abstract Process the provided data set.
* @discussion This function analyzes the input data and produces results based on the defined parameters.
* @param inputData The data to be processed.
* @param options A dictionary of processing options.
* @result An instance containing the processed results.
* @throws DataProcessingException If an error occurs during processing.
*/
- (ResultType *)processData:(NSData *)inputData options:(NSDictionary *)options;
- Imperative Tone: Begin descriptions with an imperative verb to clearly state the action performed.
- Comprehensive Tag Usage: Document all parameters, return values, and exceptions using appropriate tags.
- Consistency: Use the same style of comments and formatting throughout the codebase.
- Linking: Utilize tags like
@see
or@link
to reference related functions or documentation. - Accessibility: Ensure that documentation remains accessible and understandable even outside of specialized tools when possible.
This section outlines the conventions and guidelines for documenting shell scripts using #
comments, aiming for clarity, maintainability, and consistency.
- Shell Scripting Best Practices: Adhere to POSIX standards for portability.
- Project-Specific Conventions: Incorporate guidelines that promote consistency across all scripts within the project.
-
Rule: Every script MUST start with a shebang line specifying the interpreter.
-
Example:
#! /bin/bash
-
Rule: Include a file header containing key information about the script.
-
Content:
- Description: Brief summary of the script's purpose.
- Author: Name or alias.
- Version: Script version and release date.
- License or Disclaimer: Include any necessary legal information.
-
Example:
#!/bin/bash #------------------------------------------------------------------------------ # Script Name: backup.sh # Description: Backs up specified directories to a backup location. # Author: Your Name # Version: 1.0.0 (2024-10-15) # License: MIT License #------------------------------------------------------------------------------
-
Rule: If the script includes a license or disclaimer, place it at the top after the file header.
-
Guidelines:
- Use clear and concise language.
- Ensure compliance with legal requirements.
-
Example:
#!/bin/bash #------------------------------------------------------------------------------ # Script Name: monitor.sh # Description: Monitors system resources and logs usage statistics. # Author: Your Name # Version: 1.0.0 (2024-10-15) # License: Proprietary #------------------------------------------------------------------------------ # Disclaimer: # Provided "as is" without warranty of any kind. # Use at your own risk.
- Rule: Document functions using comments placed directly above the function definition.
- Content:
-
Function Name: Brief description of the function.
-
Arguments: Explanation of parameters.
-
Example:
# Function: check_disk_space # Checks if the available disk space is below the threshold. # Arguments: # $1 - Threshold percentage (e.g., 80 for 80%) check_disk_space() { # Function implementation }
-
-
Rule: Use inline comments judiciously to explain complex or non-obvious code segments.
-
Guidelines:
- Keep comments relevant and up to date.
- Avoid stating the obvious.
-
Example:
# Loop through the list of services and restart any that are not running. for SERVICE in "${SERVICES[@]}"; do if ! systemctl is-active --quiet "$SERVICE"; then systemctl restart "$SERVICE" # Log the restart action. logger "Restarted $SERVICE" fi done
-
Rule: Use blank lines to separate logical sections and improve readability.
-
Indentation:
- Use consistent indentation (e.g., 2 or 4 spaces).
-
Guidelines:
- Align code blocks and comments for visual clarity.
-
Example:
# Set backup directory. BACKUP_DIR="/path/to/backup" # Check if backup directory exists. if [ ! -d "$BACKUP_DIR" ]; then mkdir -p "$BACKUP_DIR" fi # Perform backup. tar -czf "$BACKUP_DIR/backup.tar.gz" /important/data
-
Rule: Comment on any security-related aspects, such as handling sensitive data.
-
Guidelines:
- Avoid hardcoding sensitive information.
- Explain the use of any security mechanisms.
-
Example:
# Read database credentials from a secure file. # Ensure the credentials file has restricted permissions. source "/secure/path/db_credentials"
- Descriptive Headers: Use headers to provide essential information about the script and its functions.
- License and Disclaimers: Include necessary legal notices to inform users of their rights and responsibilities.
- Consistency: Maintain a uniform style for comments, indentation, and formatting across all scripts.
- Portability: Write scripts that adhere to POSIX standards for compatibility across different systems.
- Error Handling: Implement and document error handling to make the script robust.
- Variable Use: Use variables instead of hardcoded values and document their purpose.
- Security Considerations: Be mindful of security implications and document any measures taken.
-
Example:
#! /bin/bash #------------------------------------------------------------------------------ # Script Name: monitor.sh # Description: Monitors system resources and logs usage statistics. # Author: Your Name # Version: 1.0.0 (2024-10-15) # License: MIT License #------------------------------------------------------------------------------ # Disclaimer: # Provided "as is" without warranty of any kind. # Use at your own risk. # Function: check_disk_space # Checks if the available disk space is below the threshold. # Arguments: # $1 - Threshold percentage (e.g., 80 for 80%) check_disk_space() { # Implementation } # Main script execution check_disk_space 80
-
Best Practices:
- Maintain consistency in style.
- Be mindful of security considerations.
- Use variables instead of hardcoded values and document their purpose.
- Write scripts that adhere to POSIX standards for portability.
XML-style comments, utilizing <!-- ... -->
, are used in XML, HTML, and other markup languages to include annotations or documentation within code files. This section outlines the conventions for writing XML-style comments in accordance with CEP-7, ensuring clarity and consistency across the project.
- XML and HTML Standards: Adherence to W3C standards for XML and HTML.
- Project-Specific Conventions: Incorporate guidelines that promote consistency and readability within the project's XML and markup files.
- Clarity: Comments MUST be clear and concise, providing meaningful insights into the code.
- Consistency: Maintain a consistent commenting style throughout all XML and markup files.
- Avoid Redundancy: Do not repeat information that is evident from the code structure.
-
File Headers:
- Rule: Include a comment block at, or near, the top of the file containing key information.
- Content:
- File Name: The name of the file.
- Purpose: A brief description of the file's purpose.
- Author: Name or alias of the author.
- Version: File version and last update date.
- License or Disclaimer: Any necessary legal information.
Example:
<!-- File: config.xml Purpose: Configuration settings for the application. Author: Your Name Version: 1.0.0 (2024-10-15) License: MIT License -->
-
Inline Comments:
- Rule: Use comments to explain complex sections or to provide additional context.
- Placement: Place comments directly above the code block or element they refer to.
- Formatting: Align comments with the indentation level of the surrounding code.
Example:
<settings> <!-- Enable verbose logging for debugging purposes --> <verboseLogging>true</verboseLogging> </settings>
-
Comment Syntax:
- Comments MUST begin with
<!--
and end with-->
, without any additional characters or spaces. - Avoid nested comments, as XML does not support nested comment structures.
- Comments MUST begin with
-
Indentation:
- Comments SHOULD be indented to match the surrounding code for better readability.
-
Line Length:
- Lines SHOULD NOT exceed 100 characters to maintain readability across different editors and screens.
-
Special Sections:
-
License and Legal Notices:
- Include any necessary licensing or legal information at the top of the file within the file header comment block.
-
Important Notes:
- Use comments to highlight critical information or warnings.
Example:
<!-- WARNING: Do not modify the following section unless you know what you're doing -->
-
-
Rule: SHOULD NOT use comments to disable code elements or blocks.
-
Reason: Commented-out code can become outdated and confusing. Remove unused code to keep files clean.
-
Rule: If using tools to generate documentation from XML files, ensure comments are properly formatted to be compatible with those tools.
-
Guidelines:
- Use consistent formatting and tagging if required by the documentation generator.
-
Maintainability:
- Keep comments up-to-date with code changes to prevent misinformation.
-
Clarity:
- Write comments that are easily understandable by other developers and stakeholders.
-
Consistency:
- Use a uniform style for headers, inline comments, and formatting across all XML and markup files.
-
Accessibility:
- Ensure that comments do not interfere with XML parsing or rendering processes.
<!--
File: settings.xml
Purpose: Defines user preferences and application settings.
Author: Jane Doe
Version: 2.1.3 (2024-10-15)
License: Apache 2.0
-->
<configuration>
<!-- User Preferences -->
<preferences>
<!-- Set to 'true' to enable dark mode interface -->
<darkMode>true</darkMode>
<!-- Default language for the application -->
<language>en-US</language>
</preferences>
<!-- Application Settings -->
<settings>
<!-- Maximum number of concurrent users -->
<maxUsers>500</maxUsers>
<!-- Enable detailed logging -->
<detailedLogging>false</detailedLogging>
</settings>
<!-- System Configurations -->
<system>
<!-- Path to the system logs directory -->
<logPath>/var/logs/app</logPath>
</system>
</configuration>
-
Editors and IDEs:
- Many XML editors provide syntax highlighting and schema validation to assist with proper formatting.
-
Linting and Validation Tools:
- Use tools like
xmllint
to validate XML files and ensure they are well-formed and adhere to schemas or DTDs.
- Use tools like
-
Documentation Generators:
- If the project uses tools to generate documentation from XML files (e.g., XSLT transformations), ensure that comments are structured appropriately for these tools.
- Sphinx: For Python documentation.
- Javadoc: For Java documentation.
- DocC: For Swift and Objective-C documentation.
- Doxygen: For C and C++ documentation.
- Flake8: For Python code and docstring linting.
- Checkstyle: For enforcing Java coding standards.
- ClangFormat: For formatting C, C++, Objective-C code.
- ShellCheck: For linting shell scripts.
[flake8]
select = C,E,F,W,B,B950
ignore =
D203, # 1 blank line required before class docstring
D212, # Multi-line docstring summary should start at the first line
docstring-convention = google
docstring_style = google
# conf.py
extensions = [
'sphinx.ext.napoleon',
'autodoc2',
'sphinx.ext.autosummary',
'sphinx.ext.githubpages',
'myst_parser',
'sphinx.ext.doctest',
'sphinx.ext.todo',
'sphinx.ext.linkcode',
'sphinx.ext.viewcode'
]
# .clang-format
ColumnLimit: 100
Adhering to the documentation style guidelines defined in CEP-7 will foster consistency and clarity across the project's codebase. Contributors are encouraged to familiarize themselves with these standards and integrate them into their development processes. As the project evolves, this CEP may be updated to accommodate new languages, tools, or best practices.