Commenting code


My notes on different commenting styles for swift .

Code documentation:

  • Commenting is vital when creating complex systems. So much resolution about how the method came to be and it’s artefacts and gotchas are lost if there is no documentation in the code.
  • I usually include massive amounts of comments in the code because when I later revisit the code a year later, my initial thinking has disappeared and I need something to accelerate my reasoning to get back into the code.
  • I also leave references to where parts of the solution was found, like stackoverflow links or other github projects, or github-issues where the solution was discussed. To give credit where credit is due.
  • Personally I use a commenting style that is closer to java-doc as a lot of people know it and it feels universal. It even renders to apples dialog boxes like bellow:
 /**
  * A method that returns awesome colors
  * - Parameters:
  *   - color: only awesome colors allowed
  *   - alpha: only awesome alpha values allowed
  * - Returns: A color with new alpha value
  */
 static func test(color: UIColor, alpha: CGFloat) -> UIColor{
     _ = color
     _ = alpha
     return color.withAlpha(alpha)
 }

Hold down the alt key and press the method name from a caller. And this dialog will pop up

img

Java-doc (Naked):

/*
  When you copy/paste, indentation is lost, also it's hard to see if the indentation is correct or not
       Here
*/

Obj-c era commenting:

///
/// This commenting style is pretty common in the swift community
/// One drawback is that you have to click 3 times every time you want to add another line
/// THis commenting style is used in obj-c and swift but not in many other languages
///

Java-doc style (Regular)

/**
 * This commenting style is used in many languages and is over all the most common
 * Example:
 * var temp = {
 *      //something indented. A comment style keeps indentation on copy paste.
 * }
 */

Comment style:

class Human {
    /**
     * This method feeds a certain food to a person.
     * - parameter food: The food you want to be eaten.
     * - parameter person: The person who should eat the food.
     * - returns: True if the food was eaten by the person; false otherwise.
     * - throws: see DecodingError
     */
    func feed(_ food: Food, to person: Human) -> Bool {
        // ...
    }
}

Mentioning classes, variables etc:

Use code ticks
/**
 * This does something with a `UIViewController`, perchance.
 * - warning: Make sure that `someValue` is `true` before running this function.
 */
func myFunction() {
    /* ... */
}

Expressive comment style

/**
 * Writes the textual representation of each    ← Summary
 * element of `items` to the standard output.
 *                                              ← Blank line
 * The textual representation for each item `x` ← Additional discussion
 * is generated by the expression `String(x)`.
 *
 * - Parameter separator: text to be printed    ⎫
 *   between items.                             ⎟
 * - Parameter terminator: text to be printed   ⎬ Parameters section
 *   at the end.                                ⎟
 *                                              ⎭
 * - Note: To print without a trailing          ⎫
 *   newline, pass `terminator: ""`             ⎟
 *                                              ⎬ Symbol commands
 * - SeeAlso: `CustomDebugStringConvertible`,   ⎟
 *   `CustomStringConvertible`, `debugPrint`.   ⎭
 */
 public func print(_ items: Any..., separator: String = " ", terminator: String = "\n"){}

Expressive comment style (w/ Markdown)

If the code is complicated or unusual etc:

/**
 * ## Feature Support
 *
 * This class does some awesome things. It supports:
 *
 * - Feature 1
 * - Feature 2
 * - Feature 3
 *
 * ## Examples
 *
 * Here is an example use case indented by four spaces because that indicates a
 * code block:
 *
 * let myAwesomeThing = MyAwesomeClass()
 * myAwesomeThing.makeMoney()
 *
 * ## Warnings
 *
 * There are some things you should be careful of:
 *
 * 1. Thing one
 * 2. Thing two
 * 3. Thing three
 */

Swift syntax keywords:

The keywords available in the swift commenting syntax

  • Attention
  • Author
  • Authors
  • Bug
  • Complexity
  • Copyright
  • Date
  • Experiment
  • Important
  • Invariant
  • Note
  • Parameter
  • Parameters
  • Postcondition
  • Precondition
  • Remark
  • Requires
  • Returns
  • SeeAlso
  • Since
  • Throws
  • ToDo
  • Version
  • Warning

Codebases that are heavily commented:

https://github.com/IBM-Swift/Kitura https://github.com/CosmicMind/Motion https://github.com/CosmicMind/Material

In closing (Comment or not to comment)

Not to comment:

  • some developers claim that if the code is well written then there is no need to comment the code
  • some developers claim that documentation is never updated so it becomes outdated etc

To comment:

  • Applications used to be simple primitive scripts that was easy to reason about. Today apps are increasing in complexity and some are even becoming platforms and are no longer easy to reason about. Therefor we need context in the slice we are currently working in, as it’s close to impossible to understand the whole structure at any one point.
  • If you go in as a swat team to fix a one-off bug. If there is contextual comments. It will save you a lot of time when trying to reason about implications.
  • Having contextual comments also avoids deprecating your dev skills. As you decrease them if you spend your day’s wandering clueless through wades of code. As oppose to spending your time creating things the proper way, nurturing things, instead of fixing someone elses rush job.
  • The main point about contextual-code-comments is that we developers have a finite amount of brain bandwidth available each day. Most efficiently spent on solving problems, not trying to understand intent. We developers write so much code in lots of different places that we quickly lose our bearings. As such we need clues in the code to derive context blazing fast and just get going. surfing on top of the wave, not under it.
  • When you have code-base that is thoroughly commented, you can use external services to auto generate searchable Help documents. Similar to apples own help documents.
  • Write a documentation comment for every declaration. Insights gained by writing documentation can have a profound impact on your design, so don’t put it off.

Resources: