Use AI to Assist with Effective Writing [DW5]
Tip DW5
Even if you are not an expert on the written communication tips outlined above, that doesn’t mean you can’t write effective comments. Nowadays, we have many AI technologies based on LLMs (like ChatGPT) that can improve existing comments or even add new comments to code without them. If you have safe access to such AI technologies, don’t hesitate to use them to improve your comments and learn along the way.
WARNING: Code (including comments) may contain proprietary, security-conscious, or otherwise sensitive information. Always make sure you have organizational approval before feeding code/comments to an LLM. Many LLM services are hosted on the Internet, but it’s possible to set up self-hosted LLM services.
For example, a prompt of
Update the following C++ code to:
Have better variable names.
Have better comments.
Better style.
was given to ChatGPT for the following code:
int Factorial(int n)
{
if (n < 0) return -1; // Handle negative input
if (n == 0) return 1;
int result = 1;
for (int i = 1; i <= n; ++i)
{
result *= i;
}
return result;
}and it gave back the following result:
// Calculates the factorial of a given non-negative integer.
// If the input is negative, returns -1 to indicate an error.
//
// @param n The integer for which the factorial is calculated.
// @return The factorial of the given integer, or -1 if the input is negative.
int CalculateFactorial(int number) {
// Handle negative input by returning -1.
if (number < 0) {
return -1;
}
// The factorial of 0 is defined as 1.
if (number == 0) {
return 1;
}
int factorial = 1;
// Calculate the factorial by multiplying each integer from 1 up to `number`.
for (int i = 1; i <= number; ++i) {
factorial *= i;
}
return factorial;
}That result lacks many features that we cover in this training, but it at least includes some comments that communicate more than the original code did.