A Guide to Write Code Comments with ChatGPT
How to Make Your Code Tell a Clear and Understandable Story with Comments
Sometimes, when I look at my friends' computer code, it's like trying to read a book with no words. It's because they forget to explain what they're doing, like telling a story without any pictures. Sometimes, stakeholders want to know what's happening in the code,. But don't worry, ChatGPT can help!
Here, I'll show you how to use ChatGPT to add comments that are clear and simple to explain your code.
Understand the Purpose of Code Comments
Before you write notes in your code, it's good to know why they're helpful. These notes do three important things:
1. Explain What the Code Does: Notes are like explanations that tell us what the code is doing. It's like telling a story about the code.
2. Keep Important Info: Notes can also have important stuff like the names of things in the code or special things the code needs to work.
3. Make Code Easier: When the code has notes, it's like making it simpler to fix and understand when something goes wrong. It's like making sure you can read and fix your homework easily.
Identify Code Sections to Comment
Take a peek at your code and find the parts that might need explanations. These could be the tricky bits or the parts that are a bit hard to understand. Think of them like adding notes to your story so others can follow along better.
Decide on Comment Style
Pick one way to write your notes in your code and stick to it. It's like deciding on a colour for your drawings and using it all the time. You can also make your decision based on your company's default or traditional commenting style.
Common styles include;
1. Single-line Comments: Use double slashes (//) for brief comments on a single line.
# Calculate the total sum of values in the array
2. Multi-line Comments: Use triple quotes (''' or """) for longer comments spanning multiple lines.
'''This function takes two arguments and returns their sum.
Arguments:
- num1: The first number
- num2: The second number
'''
When you write notes, use simple words that everyone can understand. Don't use fancy or confusing words. Make your notes short and clear. Don't say things that are easy to see in the code. Explain why you did something, not just what you did. And remember, when you change your code, change your notes too. Keep them updated so they still make sense!
Conclusion
Keep in mind that ChatGPT is an AI model and its comments may not always be perfect.
It’s always a good idea to review the generated comments and make any necessary edits before using them in your code.
Your support is invaluable
Did you like this article? Then please leave a share or even a comment, it would mean the world to me!
Don’t forget to subscribe to my YouTube account HERE, Where you will get a video explaining this article!