ChatGPT for Web Developers
Written by Timi Omoyeni
As software engineers, we constantly hear about the latest frameworks, plugins and languages… each promising to be where the future is headed. As a result, an important skill in our career is learning about these new tools and choosing when, if, and how to adopt them.
Recently, AI has presented itself as a tool that can be quite useful in our everyday lives with the emergence of different AI-powered products.
While there have been valid shows of concern about “AI taking away our jobs,” the reality is that we can treat AI as a useful tool and explore how we can integrate it into our regular work to enable us to work more efficiently and effectively, as well as automate repetitive tasks (like generating templates), debug or explain blocks of code, and aid in problem-solving in our day-to-day work.
An example of this tool is OpenAI’s ChatGPT.
ChatGPT
ChatGPT, which stands for Chat Generative Pre-trained Transformer, is an AI program launched in November 2022 by OpenAI. The model is based on a transformer architecture and was trained on a vast amount of text data using unsupervised learning methods, allowing it to generate natural language responses that are often highly coherent and contextually relevant.
It was designed to generate human-like responses to text-based inputs, such as questions or prompts. It can be used as a chatbot in conversational interfaces, virtual assistants, customer service systems, and other applications where human-like interactions are desired… For most of us in the tech scene, our favorite part of ChatGPT is its ability to read, write, understand, and even debug code in multiple languages.
ChatGPT in Programming
During the development of ChatGPT, part of the text data it was trained on was programming languages, code snippets, documentation, and discussions around how such code is used (StackOverflow, etc.).
As a result, it has learned the syntax, structure, and semantics of a number of programming languages, making it capable of identifying and interpreting code snippets written in any of these languages, as well as its intended purpose and how it fits into a larger codebase.
With ChatGPT being capable of all these things, it has led to software engineers getting creative with it and making it a part of their workflow.
Let’s take a look at some of the ways it is being used.
Debugging Code with ChatGPT
During development, there are times when we are faced with bugs, errors, and issues in our code, and we often spend “too much” time trying to debug them.
With ChatGPT being able to read and understand code in several languages, developers have chosen to take advantage of this ability and use it to cut down on the time spent debugging by using it to do any of the following tasks:
- Error message interpretation: It’s common to be faced with errors and error messages in our browser or terminal. Sometimes, we are familiar with these error messages and know how to fix them without having to check Stack Overflow or Google.
- But other times, we have no clue about how to fix it and so we resort to Google with the hopes of finding a relevant response buried in the search results. Now that we have ChatGPT, it’s possible to get direct help interpreting these cryptic error messages, and even receive solutions for how to resolve it.
- Let’s take this as an example:
- Assuming we see this error message in the browser during development and have no idea how to fix it, we can copy the entire error message (along with the stack trace), or just the error message , and ask ChatGPT it.
- or this:
- Based on this response, we can see that ChatGPT tries to understand the error message and provides insight into what it understands from it. It even can provide more **information about the error message when we provide it with more information about the error.
- It helps to explain the cause of the error, where exactly we can find the issue, and how to fix it, saving the engineer some precious time.
- Code Comments: Writing comments in code has been one of the controversial topics in software engineering as some set of people believe they are merely an indication of badly written code and should not exist, while others believe that well written comments are an important practice that helps improve code readability, maintainability, and collaboration among team members.
- Luckily, ChatGPT can also help generate comments or add suggestions for specific lines of code. This can come in handy in situations where we feel comments can help provide a bit of context to complex logic.
- Let’s ask ChatGPT to add comments to this function:
const uploadContractDocument = async (array) => {
url.value = array;
document.value.url = array[0];
const id = route.params.id;
const payload = {
id,
doc: document.value,
};
const response = await contractStore.uploadContractDocument(payload);
const { data } = response;
const { message } = data;
generalStore.setNotification({
type: "success",
heading: "Produce successfully",
text: message,
});
await contractStore.fetchContractInfo(id);
emit("close-form");
};
We’ll see that it gives us this response:
// This function is called when a contract document is uploaded
// It takes an array of file objects as an argument
const uploadContractDocument = async (array) => {
// Set the URL of the file to be the first file in the array
url.value = array;
document.value.url = array[0];
// Get the ID of the contract from the current route
const id = route.params.id;
// Create a payload object to send to the server
const payload = {
id,
doc: document.value,
};
// Call the uploadContractDocument method from the contractStore to upload the document
const response = await contractStore.uploadContractDocument(payload);
// Get the response data and message
const { data } = response;
const { message } = data;
// Set a notification message to let the user know that the upload was successful
generalStore.setNotification({
type: "success",
heading: "Produce successfully",
text: message,
});
// Fetch the updated contract information from the server
await contractStore.fetchContractInfo(id);
// Emit an event to close the form where the document was uploaded
emit("close-form");
};
This is particularly impressive considering I wrote the code a while ago and reading the comments actually helped me remember and understand exactly what each line of code was doing. If ChatGPT’s code comments can help you understand your own code, surely it can help other developers with whom you’e collaborating.
- Code Optimization and Summary: After successfully writing working code, we often need to go over our code and clean it up into a nicer, DRYer, more efficient version. Sometimes, developers struggle with this and end up either leaving the code in need of cleanup or failing to do a good job of refactoring it.
- With ChatGPT, we can easily get pointers and suggestions on how to optimize our code and make it more efficient or easy to understand.
- Using the same
uploadContractDocument
function from earlier, this is what we get when we ask ChatGPT to optimize the function for us:
// Uploads a contract document, updates notification, and fetches contract info
// Uses url, document, id, payload, response, data, message, and emits "close-form"
const uploadContractDocument = async (array) => {
url.value = array;
document.value.url = array[0];
const { data: { message } } = await contractStore.uploadContractDocument({
id: route.params.id,
doc: document.value,
});
generalStore.setNotification({
type: "success",
heading: "Produce successfully",
text: message,
});
await contractStore.fetchContractInfo(route.params.id);
emit("close-form");
};
const uploadContractDocument = async (array) => {
url.value = array;
document.value.url = array[0];
const { data: { message } } = await contractStore.uploadContractDocument({
id: route.params.id,
doc: document.value,
});
generalStore.setNotification({
type: "success",
heading: "Produce successfully",
text: message,
});
await contractStore.fetchContractInfo(route.params.id);
emit("close-form");
};
We can see here that it has gotten rid of id
and payload
and just created the object directly inside the action being dispatched contractStore.uploadContractDocument
.
We can also see that it has gotten rid of the response
variable and destructured the response to extract message
directly from data
. Personally, I hadn’t thought to do that originally!
ChatGPT can also be used to summarize longer blocks of code and this can make it easier to identify potential issues or errors. This can come in handy when trying to understand what is going on in a component, class, or function and is particularly useful when going through someone else’s code or during a code review.
Automating Repetitive Programming Tasks with ChatGPT
There are quite a number of things that we do in our day-to-day work that are repeated during the development cycle, including things like writing boilerplate code, generating test cases, code optimization/refactoring… It’s time-consuming, boring (and because of this: error-prone) having to repeat a particular process countless times.
Instead, ChatGPT can be trained to automate these tasks, saving time and reducing the risk of errors while ensuring best practices and conventions and followed.
For example, ChatGPT can be trained to generate boilerplate code for common programming tasks such as setting up a new project, creating a new class, or generating a form in any language of your choice.
I asked ChatGPT to generate a signup form with fName, lName, email, mobile, and password fields in Vue 3 and it returned this:
<template>
<form @submit.prevent="submitForm">
<div>
<label for="first-name">First Name:</label>
<input type="text" id="first-name" v-model="formData.firstName" required />
</div>
<div>
<label for="last-name">Last Name:</label>
<input type="text" id="last-name" v-model="formData.lastName" required />
</div>
<div>
<label for="email">Email:</label>
<input type="email" id="email" v-model="formData.email" required />
</div>
<div>
<label for="mobile">Mobile:</label>
<input type="tel" id="mobile" v-model="formData.mobile" required />
</div>
<div>
<label for="password">Password:</label>
<input type="password" id="password" v-model="formData.password" required />
</div>
<button type="submit">Submit</button>
</form>
</template>
<script>
import { reactive } from 'vue';
export default {
name: "MyForm",
setup() {
const formData = reactive({
firstName: "",
lastName: "",
email: "",
mobile: "",
password: "",
});
const submitForm = () => {
// handle form submission here
};
return {
formData,
submitForm,
};
},
};
</script>
Here, we can see that we would have saved time trying to write this code from scratch by ourselves, even if it requires some edits as we asked for fName
and lName
but it instead used firstName
and lastName
.
It’s important to note that ChatGPT isn’t always going to be right and it can sometimes mix things up on the first try. But it can learn from your inputs and replies in order to offer an improved solution.
Speaking of the limitations of ChatGPT…
Limitations of ChatGPT
While ChatGPT can understand code and can be useful in the ways listed above and more, it cannot do all the work for you or replace you as an engineer.
ChatGPT lacks the context of your larger codebase. It can only process the block of code that has been provided to it, whereas this context could actually play an important role in the way the code is written and what practices are followed.
ChatGPT’s knowledge of code and the quality of its responses is based on the quality of the data that it was trained on. For instance, if an update was made to a language or framework after the training, ChatGPT would be unable to provide accurate information relating to that language.
Finally, ChatGPT is not a senior developer with years of practical experience building software. It is not able to offer the same practical insights into software engineering problems and advice that a human could, based on real-world experience.
Having said that, it’s safe to say that software developers can consider ChatGPT like a programming partner. It can help us work faster, saving us time on menial tasks, and even offer solutions for how to improve our code’s efficiency and readability.
Originally published at https://www.vuemastery.com on March 2, 2023.