jamelkenya.com

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.

Visual representation of coding efficiency

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.

README example for application clarity

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.

Share the page:

Twitter Facebook Reddit LinkIn

-----------------------

Recent Post:

Computer Models in Research: Myth vs. Reality in Animal Testing

This article explores the misconception that computer models are replacing animal testing in research.

Transforming Relationships: One Key Change for Lasting Impact

Discover how one vital shift in mindset can enhance your relationships and personal well-being.

Reclaiming Control: Breaking Free from Pornography Addiction

Explore the journey of overcoming porn addiction and reclaiming control over your life, relationships, and self-worth.

# Is Life on Earth Improving? A Humorous Look at Progress

Exploring the humorous signs of progress in modern life and reflecting on the notion that despite challenges, the world is improving.

Embracing Compassionate Leadership: A Transformative Journey

Discover the power of compassionate leadership through personal growth and the importance of supporting others in their journeys.

# Lessons Learned from a Tech Interview Failure: Insights and Tips

Reflecting on a failed tech interview, this article offers insights and tips to help you navigate similar challenges in the future.

Innovative Use of Salt Solutions to Combat Microbial Growth

Exploring the effectiveness of salt-based solutions in reducing microbial growth on various fabrics.

What Happens to Your Blood Sugar When You Skip Breakfast?

Discover the effects of skipping breakfast on blood sugar levels and learn how to mitigate spikes with healthier lunch options.