Thursday, June 22, 2023

Tips for Generating Code With ChatGPT

Tips for Generating Code With ChatGPT

ChatGPT is a true superpower not just at writing, but also at generating code. Getting started with ChatGPT is straightforward, but if you want to get the most out of it, then you need to learn how to craft good prompts.

Prompts are instructions or discussion topics that you provide for the ChatGPT AI model to respond to. It can be a question, statement, or any other query that you want to spark creativity, reflection, or engagement.

There are several hidden prompts and formulas that you really need to know about to use ChatGPT effectively. Implement these formulas in your prompts and get the best results from ChatGPT.

Be Specific With Your Prompts

When using ChatGPT, you want to avoid overly simplistic prompts. Also, the more specific you can be in your requests, the better.

The way you can look at this is not to treat ChatGPT as this vending answer machine that you put tokens in and have the answers spit out to you. Instead you want to treat ChatGPT as your personal assistant (whether it's for generating content or code).

To make your queries as detailed and specific as possible (and get the best answers), here's the basic structure you'd want to use generally whenever you are creating a prompt: 

  • specify the action you want to perform (it could be to edit, write or critique)
  • follow that up by telling ChatGPT what format you want it to output (JSON, JavaScript, Python, etc.)
  • conditions and parameters to apply
  • a role or style (this is optional)

Here's an example of a query that contains all of the parts specified above:

1
// Write a function in JavaScript that takes in a string,

2
// then returns the first three and last three characters.

3
// The function should not exceed four lines of code

4
// Use best coding practices

So the action here is to write function that returns the first and last three characters from a string. The format we want it to return is JavaScript. The condition is that we want it to take no more than three lines. The style here is to use best coding practices.

This is what ChatGPT spits out:

1
function getFirstAndLastThreeCharacters(str) {
2
  const firstThree = str.slice(0, 3);
3
  const lastThree = str.slice(-3);
4
  return `${firstThree}${lastThree}`;
5
}

The actual screenshot is as follows.

Screenshot of function generated by ChatGPTScreenshot of function generated by ChatGPTScreenshot of function generated by ChatGPT
Screenshot of function generated by ChatGPT

Because we were specific in what we asked it for in our prompt, this is a lot more nuanced and specific to what we wanted compared to if we asked something more generic.

Another great thing about generating code with ChatGPT is that it explains the code as well. This is super helpful if you're new to programming or don't understand the generated code.

If you're not satisfied with the answer, click the "regenerate" button to generate a different answer. You can also modify your prompt and make it more specific, if it helps.

Assign a Tone, Style or an Audience

Oftentimes you might be generating code for a specific audience, such as beginners (this is common if you're writing code related tutorial). Perhaps you want to generate code that adheres to a specific coding style or convention (e.g. EMCAscript or TypeScript).

In such cases, you're to inform ChatGPT of the style and tone to adopt, or the audience to write for. To do this, you'd typically add the following statement to your prompt: "Write in X tone", "write in X language", or "write for X audience".

Here's an example of a query that tells ChatGPT what language to adhere to when generating the code:

1
// Write an infinite loop in JavaScript strictly in ES6 language

This is going to be the output:

1
const infiniteLoop = () => {
2
  while (true) {
3
    // Your code here

4
  }
5
};

Rather than use a regular function, ChatGPT used the an ES6 arrow function syntax (() =>) to define the function infiniteLoop, as per our request. You can do the same for other programming languages, libraries and frameworks.

Bring in the Experts

If you're still new to programming, ChatGPT can play the role of an expert for you. You can ask it to review your code and offer feedback on how to improve it. The prompt you'd use is: You are a (role). Do (action)

For example:

1
// You're are an expert JavaScript developer. 

2
// Review my code and give me feedback on how I 

3
// can improve it and make it more concise

Beneath the query, you'll then paste in the code you want ChatGPT to review and click enter. In return, ChatGPT will review your code and offer feedback on how to improve it.

I asked ChatGPT to review my function for checking whether a string is a palindrome or not. ChatGPT gave me an improved version of my code in return:

1
function isPalindrome(string) {
2
  const len = string.length;
3
  for (let i = 0; i < Math.floor(len / 2); i++) {
4
    if (string[i] !== string[len - 1 - i]) {
5
      return false;
6
    }
7
  }
8
  return true;
9
}

It also gave me a few suggestions to improve its readability and conciseness:

Screenshot of suggestions by ChatGPTScreenshot of suggestions by ChatGPTScreenshot of suggestions by ChatGPT
Screenshot of suggestions by ChatGPT

With this feature, you can review any code to make sure it meets best coding standards. Keep in mind that ChatGPT can generate faulty code. So you need to test-run the code to confirm that it gives the expected output before pushing it to production.

Use ChatGPT to Get Unstuck

As a software developer, you're bound to run into problems during development. Perhaps your code isn't working and you don't know why. Or you're not sure how to create a function that performs a specific task.

The best place to find such solutions used to be on forums like StackOverflow and Reddit. But now you can use ChatGPT to solve any of your coding related problems.

The best thing about using ChatGPT is that it's instantaneous and you don't have to browse through articles or solutions to find what you want. Each solution also comes with an in-depth explanation, which is something you may not find with the answers you get from StackOverflow or Reddit.

Keep Iterating

You probably will not get exactly what you want right out of the gate, but that is expected. Be prepared to ask ChatGPT to rewrite things, regenerate code blocks, or make adjustments to code. Alternatively, you can simply redo your entire prompt and get something completely new from it.

The key here is to have a collaborative conversation with ChatGPT that goes back and forth, instead of just putting in one prompt and expecting one thing and trying again. 

The really cool thing about ChatGPT is that you can have a continuous conversation with it, and it will remember your previous interactions. It'll be able to remember the context of other answers that it gives you within a particular chat.

Conclusion

The key to using ChatGPT effectively are well-crafted prompts. Your prompts need to be specific, concise and as detailed as possible. It should contain an action, the output format, one or more conditions and a role or style to use (this is optional).

ChatGPT can not only generate code, but also review your own code for errors and provide feedback on how to improve it. When used correctly, ChatGPT can help smoothen the process of developing applications. But if you an AI-tool specifically tailored for programming, check out GitHub Copilot


No comments:

Post a Comment