Enhancing Code Quality with ChatGPT: Comments, Refactoring, and More
Written on
Chapter 1: Introduction to ChatGPT for Developers
Welcome to this article where we explore how ChatGPT can be utilized for commenting, refactoring code, and generating README files. As a developer, I recognize the significance of writing clean and organized code, along with the necessity of clear documentation. I'm thrilled to share how ChatGPT can facilitate these processes, enhancing your efficiency and effectiveness.
Midjourney prompted by Michael King
In this guide, I will take you through the steps of employing ChatGPT to comment on and refactor your code, as well as how to create comprehensive README files. By the end, you will have gained insights into how ChatGPT can elevate your coding skills and enhance the user-friendliness of your projects. Let's begin!
As a devoted coder, I often find myself engrossed in my work, spending hours at the computer. While this intense focus is often productive, it does have drawbacks. One such drawback is that my code sometimes ends up lacking sufficient comments, which can make it challenging for others—and even myself—to grasp the logic later.
This prompted me to test ChatGPT by asking it to assist me in commenting on my unorganized code. For this demonstration, I used the code from an application I developed called the Art Style Prompt Generator. I was curious to observe how ChatGPT would manage this task and whether it could enhance the readability of my code. So, let’s delve into the findings!
The first video, "Generating Code Comments - ChatGPT," illustrates how to use ChatGPT for adding descriptions and comments effectively.
Chapter 2: The Art Style Text Prompt Generator
Greetings to all AI, Python, and design enthusiasts! Are you weary of endlessly searching for the ideal prompt for your projects?
My initial messy Python script was as follows:
import PySimpleGUI as sg
import yaml
import pyperclip
def get_options(file_path):
with open(file_path, 'r') as file:
options = yaml.load(file, Loader=yaml.FullLoader)return options
options = get_options('options.yaml')
layout = [[sg.Column([[sg.Text(key), sg.Combo(options[key], key=key)] for key in options.keys()])]]
layout.append([sg.Text('Enter image topic:'), sg.InputText(key='topic')])
layout.append([sg.Button('Submit'), sg.Button('Exit')])
layout.append([sg.Text('Output: '), sg.InputText(key='output', size=(40,1))])
layout.append([sg.Button('Copy to clipboard', key='copy', visible=False)])
window = sg.Window('Image Prompt Generator', layout)
while True:
event, values = window.read()
if event == 'Submit':
output = values['topic'] + ', ' + ', '.join([values[key] for key in options.keys()])
window['output'].update(output)
window['copy'].update(visible=True)
if event == 'copy':
pyperclip.copy(values['output'])if event in (None, 'Exit'):
break
window.close()
As I analyzed the newly commented code, I was genuinely impressed. The comments provided by ChatGPT were not only informative but also meaningful, effectively clarifying the purpose of each code section. However, I identified one more area for improvement.
Upon reviewing my code, I recognized that its monolithic structure could benefit from refactoring. I was eager to see if ChatGPT could assist with this, so I gave it the green light to proceed.
The second video, "ChatGPT Refactoring Code," demonstrates how to improve code organization and readability using ChatGPT.
Refactoring the Code
Here’s the refactored version:
import PySimpleGUI as sg
import yaml
import pyperclip
def get_options(file_path):
"""
Read options from file and return them. :param file_path: path of the options file :return: options in a dict
"""
with open(file_path, 'r') as file:
options = yaml.load(file, Loader=yaml.FullLoader)return options
def create_layout(options):
"""
Create the layout for the GUI using the options. :param options: dict of options :return: layout list
"""
layout = [[sg.Column([[sg.Text(key), sg.Combo(options[key], key=key)] for key in options.keys()])]]
layout.append([sg.Text('Enter image topic:'), sg.InputText(key='topic')])
layout.append([sg.Button('Submit'), sg.Button('Exit')])
layout.append([sg.Text('Output: '), sg.InputText(key='output', size=(40,1))])
layout.append([sg.Button('Copy to clipboard', key='copy', visible=False)])
return layout
def handle_events(window, options):
"""
Handle the events of the GUI. :param window: PySimpleGUI window :param options: dict of options
"""
while True:
event, values = window.read()
if event == 'Submit':
output = values['topic'] + ', ' + ', '.join([values[key] for key in options.keys()])
window['output'].update(output)
window['copy'].update(visible=True)
if event == 'copy':
pyperclip.copy(values['output'])if event in (None, 'Exit'):
break
def main():
options = get_options('options.yaml')
layout = create_layout(options)
window = sg.Window('Image Prompt Generator', layout)
handle_events(window, options)
window.close()
if __name__ == '__main__':
main()
After running the refactored code, I was genuinely astonished. It executed flawlessly and was far more organized and comprehensible than before. I never anticipated that ChatGPT could significantly enhance the structure of my code.
Finally, I wanted to challenge ChatGPT with one last task: creating a concise README for my application. I was curious if it could help make the application more user-friendly and provide comprehensive insights for other developers.
As I reviewed the README generated by ChatGPT, I was once again impressed. It was clear, succinct, and contained all the essential information for other developers to grasp the application's purpose and functionality. ChatGPT had indeed exceeded my expectations in every aspect.
With ChatGPT at my side, I can now focus on what I excel at—coding—without being bogged down by the tedious tasks of commenting, refactoring, or writing README files. The value that ChatGPT brings to developers like myself is truly remarkable, and I can confidently say it will be my go-to tool moving forward. Kudos to OpenAI for creating such a powerful asset!
In conclusion, I hope this article has enlightened you on how ChatGPT can aid in commenting, refactoring, and generating README files for your projects. As a coder, I understand how vital it is to maintain well-structured and documented code. I encourage you to subscribe to my channel and newsletter for more tips and tricks on leveraging ChatGPT to enhance your coding skills and improve project usability. You won't regret it!
And if you're feeling generous, consider buying me a coffee at www.buymeacoffee.com/kingmichael. Your support would greatly motivate me to continue producing content you love.