Monday, April 08, 2024

Comments in code written by AI

The general "best-practice" guidance for code comments is that they should explain "Why the code is there, rather than what it does."

When code is generated by AI/LLMs (CoPilot and the like) via a prompt (rather than line completions), it can be beneficial to include the command (prompt) provided to the "AI". This is useful as the generated code isn't always as thoroughly reviewed as code written by a person. There may be aspects of it that aren't fully understood. It's better to be honest about this.

What you don't want is to come to some code in the future that doesn't fully work as expected, not be able to work out what it does, not understand why it was written that way originally, and for Copilot's explanation of the code to not be able to adequately explain the original intent.

// Here's some code. I don't fully understand it, but it seems to work.
// It was generated from the prompt: ".
// The purpose of this code is ...

No, you don't always need that first line.

Maybe xdoc comments should include different sections.

"Summary" can be a bit vague.

Maybe we should have (up to) 3 sections in the comments on a class or method:

  • Notes for maintainers
  • Notes for consumers
  • Original prompt

Writing a comment like this may require some bravery the first few times you write such a thing, but it could be invaluable in the future.


Post a Comment

I get a lot of comment spam :( - moderation may take a while.