Comment As You Code To Ensure Subtle Details Are Documented [DC2] [WHY]

Comment As You Code To Ensure Subtle Details Are Documented [DC2] [WHY]

Tip DC2

If you comment "immediately" (particularly as you discover bugs/unexpected problems), the information is fresher in your mind, so you can write better comments, and you do not have to spend time later going back to try and remember various details. You’re also less likely to forget subtleties that came up when originally working on the code. As soon as you realize something that isn’t going to be evident from the code itself, put it into a comment immediately.

 

Examples below show comments with details that would be harder to remember if commenting were done after the fact:

Example 1 - Rationale for picking a particular return type

/// \return The latest in-progress report, if one exists; /// null if no in-progress report exists. /// A shared pointer is returned to support two important scenarios: /// 1. The latest in-progress report needs to be modifiable by calling code. /// Returning a shared pointer supports calling code being able to modify /// the report and have its changes automatically reflected in the /// centralized in-memory report storage without expensive copying of /// the entire report object. /// 2. There may not always be an in-progress report, so returning a shared /// pointer supports returning null to indicate this. std::shared_ptr<Report> GetLatestInProgressReport() { // ... }

Example 2 - Rationale for why variables are captured a certain way in a C++ lambda

build_task.ReturnCodeBeingWaitedOn = std::async( std::launch::async, // It is important that these parameters be captured by value // as the memory location for them will differ later. [project, build_folder_path, build_variant]() -> int { return project->Build(build_folder_path, build_variant); });

 

Busy coding or busy meeting ad.png