We'll be giving some insights about how to use ChatGPT to increase productivity while programming, focusing specifically on what it can do from a code snippet. This article covers finding bugs, modifying code, creating tests, and some other common software development tasks with practical and easy-to-follow examples.

ChatGPT is a promising AI tool that has been changing how we face some activities. When it comes to software development, it has the potential to make us more productive, improve our code quality and even spare us from some boring and time-consuming tasks.

However, since ChatGPT is still relatively new, many of us are still trying to figure out how to extract the most of it and use it to boost our productivity while coding. And if you are willing to embrace this new technology as your new programming assistant, you probably are too.

In this article, we'll be exploring what can ChatGPT do on our behalf when provided with a code snippet.

The code

First of all, we are going to need our source code. The following code was written in JavaScript and is simple and far from perfect, so let's see what ChatGPT can help us with.

Getting started

When working on a new project, we might need a little help getting started. ChatGPT can walk us through that process by giving a step-by-step guide on how to get the code running.

Question

How can I run this code?

Response

The code is written in JavaScript. Here are the steps to run the code:

  1. Open a text editor, such as Visual Studio Code or Sublime Text.
  2. Copy and paste the code into the text editor.
  3. Save the file with a .js extension, for example, "myCode.js".
  4. Open a command-line interface, such as the terminal on a Mac or the Command Prompt on Windows.
  5. Navigate to the directory where the file is saved using the command-line interface.
  6. Type "node myCode.js" in the command-line interface and press enter.
  7. The code will run and the output will be displayed in the command-line interface.

You could also go further and ask for instructions on how to set up the environment, in case the initial instructions weren't enough.

Explaining code

Another very helpful task that ChatGPT can perform is code explanation. This can be used to understand a new project or to understand complex or confusing code. We can also extend this idea to create documentation.

Question

Explain this code.

Response

This code defines an object named "person" that contains information about a person's name, address, and hobbies. It then uses this information to construct a string message that introduces the person and lists their address and hobbies.

Here's a breakdown of what each line does:

  1. Define an object named "person" with four properties: "firstName", "lastName", "hobbies", and "address". The "hobbies" property is an array of strings, while the "address" property is itself an object with four properties: "street", "city", "state", and "zipcode".
  2. Define a variable named "fullName" by concatenating the "firstName" and "lastName" properties of the "person" object with a space in between.
  3. Define a variable named "address" by concatenating the "street", "city", "state", and "zipcode" properties of the "address" object of the "person" object, separated by commas.
  4. Define a variable named "lastHobbie" by getting the last item in the "hobbies" array of the "person" object.
  5. Define a variable named "hobbies" by taking all but the last item in the "hobbies" array of the "person" object, joining them with commas, and adding the string "and" and the "lastHobbie" variable at the end.
  6. Log a message to the console that introduces the person using their "fullName", lists their "address", and mentions their "hobbies". The message is constructed by concatenating several strings with the variables defined in the previous steps.

Formatting

When asked to format the code, ChatGPT didn't change much at first, since the code is already relatively well formatted. But when more specific instructions were provided, it was able to follow a different set of rules to perform the formatting as requested.

Question

Format this code following Prettier standard configurations and don't let any line exceed 70 characters.

Response

Here's the formatted code following Prettier standard configurations, and not letting any lines exceed 70 characters:

The code is formatted using Prettier with the printWidth option set to 70 characters. As a result, lines that exceed 70 characters are automatically wrapped onto new lines. The code is also properly indented and formatted according to Prettier's default rules. Additionally, a comma is added after the last property in the address object, which is a common practice to make it easier to add or remove properties later.

Finding bugs

ChatGPT is also capable of analyzing the code and finding bugs. In our example, although no bugs were found, it still warned us of some problems that may occur if the person object isn't defined as expected.

Question

Does this code have any bugs?

Response

Based on a quick analysis, there are no apparent bugs in this code. It appears to be correctly defining an object with properties and using those properties to construct a message that is logged to the console.

However, it's worth noting that there could be potential issues depending on how this code is used and where it's being implemented. For example, if the "person" object is being created dynamically and some properties are missing, this could cause errors in the code. Additionally, if the "hobbies" array is empty, the variable "lastHobbie" would be undefined and could cause issues when constructing the "hobbies" variable.

But, based on the code itself, it does not contain any obvious bugs.

We then changed the following line in the code in order to create a small bug:

And sent the whole code again with the exact same question. Surprisingly, even though the code still runs without errors, the AI model was able to capture that there was a bug in our logic, as seen below:

Response

Yes, there is a bug in this code. Specifically, the fullName variable is being constructed incorrectly.

Instead of concatenating person.firstName and person.firstName, it should be concatenating person.firstName and person.lastName to create the full name. So the line:

should be:

With this correction, the code should work as intended.

This is a very interesting behavior, as it shows that ChatGPT can do more than just point out obvious mistakes, such as syntax errors. It can also understand the intention behind a code, which enables it to identify a more vast set of bugs, as seen above.

Reviewing code

It's always good to have a second opinion on your work, so we asked ChatGPT to review our code and it gave a couple of suggestions on how to improve it. This is very useful to enhance the quality of your code and also to learn better coding practices. For those who work with software development, this can also be used as a first layer of review before sending the code to be reviewed by a peer, saving you both some precious time.

Question

Review this code.

Response

The code looks good overall, with clear and descriptive variable and property names.

One minor improvement could be to use template literals instead of concatenating strings with the + operator. This can make the code more readable and easier to maintain. Here's an example of how the last console.log statement could be rewritten using template literals:

Another improvement would be to add error handling in case the person object doesn't have expected properties, like firstName, lastName, hobbies, and address. If any of these properties are missing, the code will throw an error. We can add a check to ensure that these properties exist before using them.

Modifying code

After that review, we need to modify the code accordingly. So how about having ChatGPT do that for us as well?

Question

Implement what you suggested.

Response

Sure! Here's the updated code with the suggested improvements:

In this updated version, we first check if the person object has all the expected properties using an if statement. If any of the properties are missing, we log an error message to the console.

We also replaced the string concatenations with template literals in the last console.log statement for improved readability.

In this example, although ChatGPT was able to perform the requested task, we noticed that some details were overlooked. Regarding template literals, most of the code was changed. But when building lastHobbie, the concatenation " and " + lastHobbie could have also been changed to ` and ${lastHobbie}`. Regarding error handling, the check that ChatGPT returned is basic and doesn't cover all possible errors, like the hobbies array having too few elements and the properties inside the address object being undefined. Both of those cases would lead to poor construction of the console.log statement and weren't covered by the AI.

Now that we went over the code review, let's go a step further and change the code to TypeScript while adding types and interfaces.

Question

Add types and interfaces to the JavaScript code.

Response

Here's the updated code with types and interfaces:

The Address interface defines the structure of the address property of the Person interface. The Person interface defines the structure of the person object. All the variables are now declared with their respective types.

As we can see, ChatGPT added the correct types to each variable in our code. On the other hand, we might not want to type every single variable, such as the string constants fullName, address, lastHobbie and hobbies that are built at the end of the program. In that sense, it may be good to use more specific prompts and ask for changes incrementally (e.g.: "Create an interface for person" and "Create a separate interface for address").

ChatGPT has also previously warned us about the bug that might happen when the person.hobbies array does not have the length we expect. Let's fix that as well.

Question

Change how the hobbies string and the final string are created so the code works for people with 0, 1 or more hobbies.

Response

To make the code work for people with 0, 1 or more hobbies, we need to update how we create the hobbies string and the final string.

To create the hobbies string, we can check the length of the hobbies array. If it is 0, we can set the hobbies string to "nothing". If it is 1, we can just use the first element of the array. If it is more than 1, we can join the elements of the array with commas and use "and" before the last element.

To create the final string, we can concatenate the different parts using template literals and conditionally add the hobbies string.

Here's the updated code:

Output:

Now we have a code that works fine for people with one or no hobbies. Other examples of modifications you can ask for are starting to use a specific library, updating the code to match another version of some technology you are using, changing patterns (like changing how you name properties and variables), and so on.

Refactoring

Although it also falls into the modifying code category, refactoring has a more specific focus. When refactoring, we want to improve code quality without actually changing its behavior. One way to do it is by using method extraction, which means extracting some code into a separate function to make it reusable and make the whole code easier to read. Let's apply that in our code.

Question

Refactor this code to extract methods for building fullName, address and hobbies. Also extract the method that builds finalString, but give finalString a meaningful name.

Response

Here's a possible refactored version of the code with methods extracted:

Changes made:

  • Extracted the buildFullName, buildAddress, and buildHobbiesList functions to separate concerns.
  • Created a new function buildGreeting to assemble the final string using the extracted methods.
  • Renamed finalString to finalGreeting to make it more meaningful.
  • Used the extracted functions instead of directly accessing the person object's properties.

In this test, we saw that we needed to experiment with different questions until we got the result we wanted. This may be because this question had multiple demands (the extraction of 4 methods and the renaming of a variable), which makes it more complex. Again, it might be useful to ask for changes incrementally for more straightforward results.

Generating tests

Now that we are satisfied with our improved and refactored code, we can also ask ChatGPT to generate some tests for it.

Question

Generate unit tests for this code.

Response

Here are some possible unit tests for the code:

These tests cover the buildFullName, buildAddress, buildHobbiesList, and buildGreeting functions, as well as the error case in which the person object is missing required properties.

At a first glance, the tests seem to have turned out great, covering a variety of cases and having good and meaningful names. To see if they actually work, we first needed to configure Jest and export all the used entities from our code and import them into our testing file. We then saw there was an error in the last test: the type of person is not assignable to the type expected by the function buildGreeting. We were able to fix that by casting the variable to Person, as shown below.

After that, we were able to run the test suites, which gave us the following result:

Test return

As we can see, not all tests have passed. The first two fails were due to an extra comma in the hobbies array (it should expect "Reading, Coding and Hiking" instead of "Reading, Coding, and Hiking"). Regarding the last failed test, it expected an error with the message "Invalid person object - missing properties." when calling buildGreeting with an invalid Person object. That message, however, is logged (and not thrown) by the error handling code that ChatGPT implemented for us, which lies outside of the buildGreeting function and thus is not called when we run that test. Since it does make sense to have buildGreeting validate the inputted value, we chose to change the source code to make the test work instead of changing the test itself. Therefore, we moved the error handling into our function and threw the error instead of just logging it to the console. The new buildGreeting function is shown below, and we were finally able to pass all test cases.

In this example, we've seen that the AI did save us a lot of time by proposing coherent test suites, but we needed to intervene in order to get all test cases passing. On one hand, ChatGPT was able to understand the code and its domain, and thus come up with tests that cover a variety of relevant cases. On the other hand, it struggled with understanding the execution of the code and therefore predicting its exact output, which made some test cases fail. In the end, using the proposed code as a first draft and working from it is what worked best for us in this scenario.

Fixing errors

In the previous section, we discussed the testing file that ChatGPT generated, and that it had some errors which we fixed manually. This time, we are going to try and use AI's help to fix the errors as well. The first problem we needed to solve in the code was the missing imports and exports statements, so we'll start from there.

Question

I'm getting the following errors:
Cannot find name 'buildFullName'.
Cannot find name 'buildAddress'.
Cannot find name 'buildHobbiesList'.
Cannot find name 'buildGreeting'.

Response

These errors indicate that the import statements in your test file are incorrect or missing. You need to import the functions and interfaces that you want to use in your tests from the code.ts file.

Assuming that your code.ts file is in the same directory as your test file, you can add the following import statements at the beginning of your test file:

Make sure that the path in the import statement is correct and matches the location of the code.ts file.

Also, make sure that the functions and interfaces are exported from the code.ts file using the export keyword.

Following those instructions, we were able to overcome the first error. After that, we got another error for calling buildGreeting with a parameter of the wrong type.

Question

In this line:
expect(() => buildGreeting(person)).toThrowError(expectedErrorMessage);
I'm getting the following error:
Argument of type '{ firstName: string; lastName: string; }' is not assignable to parameter of type 'Person'.
Fix this without breaking the "returns an error message string when given a person object with missing properties" test.

Response

The error message indicates that the person object passed to the buildGreeting function in the test is missing the address and hobbies properties, which are required for the Person interface.

To fix this error, you can use a type assertion to cast the person object to the Person type when calling the buildGreeting function in the test. Here's the modified code:

With this change, the person object is explicitly cast to the Person type using the as keyword, which allows the test to compile without breaking the "returns an error message string when given a person object with missing properties" test.

In this example, we needed to be more careful when writing our prompt, because most of ChatGPT's suggestions involved adding the missing properties to the object in order to match the correct type. The problem with that solution is that it does not make sense in our test, since its goal is to test the behavior of the code when the properties are missing. With the question above, we were able to get what we wanted.

Now that we can finally run our tests, we are able to see that three of them don't pass, exactly as described in the previous section. Two of them fail due to an extra comma, so we'll start by investigating that.

Question

The test "returns a comma-separated list of hobbies and the word 'and' before the last hobby when given an array with multiple hobbies" failed with this message:
Expected: "Reading, Coding, and Hiking"
Received: "Reading, Coding and Hiking"
Remember that buildHobbiesList should return "nothing" when there are no hobbies in the array.

Response

To fix the test, you need to modify the implementation of the buildHobbiesList function to include the word "and" before the last hobby even when there are only two hobbies in the array. Here's an updated implementation that should fix the test:

With this implementation, the function will always include the word "and" before the last hobby, even when there are only two hobbies in the array. This should make the test pass.

As we can see, ChatGPT suggested changing the function to match the test. In this case, we also had some problems generating a response that worked, since the AI was changing the return statement's value from "nothing" to an empty string, which caused a bug. Adding that restriction to the question fixed the issue.

As that modification already fixed two of our tests, there's only one failed test remaining. The problem is caused by the fact that the error handling code is not called by the buildGreeting function. However, in every try to get AI to fix this, it suggested altering the error handling statement and didn't mention anything about calling it from our function. With that in consideration, we conclude that ChatGPT failed to identify this last problem for us.

Converting code to another language

Another task we can have ChatGPT perform for us is to write our code in another language. This is useful when you need to migrate your codebase to another technology, create a serverless function from an existing code, or convert code examples you might find online to any other programming language you need.

Question

Convert this code to Python.

Response

Here's the Python equivalent of the code:

Note that I've used Python's typing module to define the types of the function parameters and return values. The Person and Address classes are defined using the class keyword in Python. Also, instead of using backticks to create template literals (as in JavaScript), I've used f-strings (formatted string literals) in Python. Finally, I've used ValueError instead of Error to raise an exception when the Person object is invalid.

We were able to ensure that the translated code works and returns almost the same result as the original code. The only small difference is that a comma was added before "and" in "Reading, Coding, and Hiking", similar to what happened when generating the test suites. This reinforces the importance of double-checking the responses when using ChatGPT for coding.

Link to projects online

Besides using code snippets, it is also possible to provide a link to a project (or to a specific file inside a project) while chatting with the AI tool. We are going to try this by using the following code file, which can be found in this link.

Question

Create tests for the code in this file: https://github.com/romeojeremiah/javascript-projects-for-beginners/blob/master/Centimeters Converter/centimetersConv.js

Response

Here are some tests for the feetToCent function in centimetersConv.js:

The first test checks if feetToCent returns the correct output for valid input.

The second test checks if feetToCent returns undefined and logs an error message when the feet input is negative.

The third test checks if feetToCent returns undefined and logs an error message when the inch input is outside of the range 0-12.

To run these tests, as the feetToCent function is loaded using require, we first need to go to our source code and define the module exports:

After that, we were able to run all tests and verify that they all pass.

Test response OK

When analyzing the generated code, we can see that the proposed tests cover a good amount of cases and that they have meaningful names, which leads us to conclude that ChatGPT excelled at this task. However, we must also point out that this code wasn't generated on our first try. We saw that the AI was able to capture the essence and domain of the code (converting units of measure) in every try, but sometimes it generated tests for functions that aren't even implemented (some results we had tested centimetersToInches and inchesToCentimeters, or centimetersToInches, inchesToFeet and centimetersToMeters). This comes to show that ChatGPT can generate wrong information, thus we need to be very careful.

ChatGPT in software development

While doing these experiments we were able to see that ChatGPT can truly be an ally in software development, assisting us in many ordinary programming tasks. On the other hand, we also need to raise attention to the fact that it gave us false responses from time to time, like creating tests that fail, not translating the code exactly as it should, or creating tests for functions that are not defined. With that in mind, we advise you to always double-check the modified or generated code before adding it to your project and always have a critical look while interpreting the responses.

Finally, we encourage you to explore what ChatGPT offers regarding software development. In this article, we covered some of the tasks it can perform when provided with a code snippet, but the possibilities of using ChatGPT in programming are endless. We hope you can use this as inspiration on how to be a better developer with the help of AI.

Authors

Guilherme Coelho

Thais Morato