---
icon: dot
---

> **"Programs must be written for people to read and only incidentally for machines to execute."**
>
> _Famed MIT professor Hal Abelson_

## How to Write Comments

- Rule 1: **Comments should not duplicate the code.**
- Rule 2: **Good comments do not excuse unclear code.**
- Rule 3: **If you can’t write a clear comment, there may be a problem with the code.**
- Rule 4: **Comments should dispel confusion, not cause it.**
- Rule 5: **Explain unidiomatic code in comments.**
- Rule 6: **Provide links to the original source of copied code.**
- Rule 7: **Include links to external references where they will be most helpful.**
- Rule 8: **Add comments when fixing bugs.**
- Rule 9: **Use comments to mark incomplete implementations.**

[!ref text="Best practices for writing code comments" target="blank"](https://stackoverflow.blog/2021/12/23/best-practices-for-writing-code-comments/)
[!ref text="Code tells you how, comments tell you why" target="blank"](https://blog.codinghorror.com/code-tells-you-how-comments-tell-you-why/)

## Conventions in Writing Documentation Comments

For longer documentation comments, place the opening `/**` on a separate line and begin each subsequent line with an asterisk:

```kotlin
/**
 * This is a documentation comment
 * on multiple lines.
 */
```

Short comments can be placed on a single line:

```kotlin
/** This is a short documentation comment. */
```

Generally, avoid using `@param`, `@return`, etc. tags.
Instead, incorporate the description of parameters and return values directly into the documentation comment, and add links to parameters wherever they are mentioned.
Use `@param` and `@return` only when a lengthy description is required which doesn't fit into the flow of the main text.

```kotlin
// Avoid doing this:

/**
 * Returns the absolute value of the given number.
 * @param number The number to return the absolute value for.
 * @return The absolute value.
 */
fun abs(number: Int): Int { /*...*/ }

// Do this instead:

/**
 * Returns the absolute value of the given [number].
 */
fun abs(number: Int): Int { /*...*/ }
```

## Doc Tools for Comments

There are some optional tools that facilitate gathering all these comments in one place.

- [JavaDoc for Java](https://www.oracle.com/technical-resources/articles/java/javadoc-tool.html)
- [KDoc and Dokka for Kotlin](https://kotlinlang.org/docs/kotlin-doc.html)
- [TypeDoc](https://typedoc.org/)
- [JSDoc](https://jsdoc.app/)
- [PythonDoc](https://realpython.com/documenting-python-code/)
