DEV Community

Cover image for Code Smarter, Not Harder: How ChatGPT Can Simplify Your Coding Journey 🚀🔥

Posted on • Updated on • Originally published at

Code Smarter, Not Harder: How ChatGPT Can Simplify Your Coding Journey 🚀🔥

ChatGPT is the hot shit among developers right now! In this article, I’ll show you how you can benefit from this AI tool as a developer. With practical examples and insider tips, I’ll show you how to speed up your development processes and make your life easier. So let’s get started!

❓ What is ChatGPT?

What is ChatGPT? Good question. Is it a chatbot? A text generation tool? Or just another AI model that will soon make us developers obsolete? Let’s just ask it ourselves.
What is ChatGPT in 3 sentences?<br>
Now, before you panic, let me explain: ChatGPT is indeed an AI model for text generation, but it’s so much more than that. It’s a general-purpose tool that can help you as a developer get your work done faster, more effectively, and even more creatively.

But what is the secret of ChatGPT? Well, it’s based on a so-called Generative Pre-trained Transformer, or GPT for short. Sounds like a science fiction weapon, but it’s actually just an algorithm trained to generate natural language texts written by humans.

And with ChatGPT you can use this powerful tool in your development process. But be careful! ChatGPT is not a panacea and should be used with care. What you have to pay attention to, you will learn now.

Curious now? Everyone can currently use ChatGPT for free. All you have to do is create an account with your email address.

👉 How can ChatGPT be used by developers?

1. Develop code, scripts and snippets

ChatGPT can help developers generate code, scripts and snippets automatically by typing short prompts. This can save time and effort. However, it is important to ensure that the generated code meets the requirements and is thoroughly tested before deploying it. ChatGPT can also act as a “code checker” and suggest improvements.

In addition, ChatGPT can help with writing automated workflows. Overall, ChatGPT provides tremendous support for code development, but it is important to still have the skills and knowledge to write and optimize code from scratch.

I prefer to use it when generating config files. There, many parameters are needed that are rarely used and therefore you don’t have them in your head. Recently I wanted to extend an existing CI/CD environment with a test phase. The existing script looked like this:

name: Node.js CI/CD Workflow with frontend
    branches: [ "master" ]
    runs-on: ubuntu-latest
        node-version: [16.x]
    - uses: actions/checkout@v3

    - name: Use Node.js ${{ matrix.node-version }}
      uses: actions/setup-node@v3
        node-version: ${{ matrix.node-version }}
        cache: 'npm'

    - name: Build Frontend
      run: npm i --prefix client && npm run build --prefix client
       CI: false

    - name: Push to build branch
      uses: s0/git-publish-subdir-action@develop
        REPO: self
        BRANCH: build # The branch name where you want to push the assets
        FOLDER: ./public # The directory where your assets are generated
        GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # GitHub will automatically add this - you don't need to bother getting a token
        MESSAGE: "Build: ({sha}) {msg}" # The commit message
Enter fullscreen mode Exit fullscreen mode

ChatGPT then reengineered the missing step for me. I simply passed the existing config file in the prompt.

    - name: Install dependencies and run tests
      run: |
        npm install
        npm run test
        CI: true # set environment variable to run tests in CI mode
Enter fullscreen mode Exit fullscreen mode

2. Writing documentation

By simply asking ChatGPT for the documentation you want, you can have it generate structured documentation that covers all the important aspects of your code or project. Extensions for your IDE can also help with this. I will go into this in more detail later.

However, it is important to ensure that the generated documentation is complete and understandable. One should also take the time to review it and edit it if necessary before passing it on to customers or users.

I have a great example of this here. Imagine you are looking at another developer’s code and he didn’t pay attention to the naming of the functions and also didn’t create comments. By the time you look through the code, ChatGPT already has the solution for you. Or can you tell me within 10 seconds what this code does?

import random
def whatDoesThisFunction(numbers):
    for i in range(len(numbers)):
        for j in range(i+1, len(numbers)):
            if numbers[j] < numbers[i]:
                numbers[i], numbers[j] = numbers[j], numbers[i]
    return numbers
if __name__ == '__main__':
    numbers = [random.randint(1, 100) for _ in range(10)]
    sorted_numbers = whatDoesThisFunction(numbers)
Enter fullscreen mode Exit fullscreen mode

I asked ChatGPT to “Write comments in the code:”. This was the result:

def whatDoesThisFunction(numbers):
    This function takes in a list of numbers and sorts them using the bubble sort algorithm.
    for i in range(len(numbers)):
        for j in range(i+1, len(numbers)):
            if numbers[j] < numbers[i]:
                numbers[i], numbers[j] = numbers[j], numbers[i]  # Swap the values if the jth element is smaller than the ith element.
    return numbers
if __name__ == '__main__':
    numbers = [random.randint(1, 100) for _ in range(10)]  # Generate a list of 10 random integers between 1 and 100.
    sorted_numbers = whatDoesThisFunction(numbers)  # Call the function to sort the numbers.
    print(sorted_numbers)  # Print the sorted list of numbers.
Enter fullscreen mode Exit fullscreen mode

I think I do not need to say more 🙂

3. Provide food for thought

It can be frustrating to be stuck trying to solve a problem and run out of ideas. In such situations, ChatGPT can serve as a thought-provoking tool by suggesting alternative approaches and ideas. With its ability to analyze a wide range of information and recognize patterns, ChatGPT can often make unexpected and useful suggestions. While it may not always provide the perfect solution, it can help stimulate the creative process and find new ways to solve problems.

4. Test writing

When it comes to writing tests, it can be very time-consuming and tedious. But with ChatGPT you can automate this tedious task and speed up your code development process.

How does it work? By simply submitting a request to ChatGPT describing the test case you want to create. The AI engine will then automatically generate the test case code for you! This means less stress and faster code generation, so you can focus on other important tasks.

I would like to demonstrate the whole thing to you. I have here code from a middleware of an existing Rest API:

// Middleware to validate challenge parameters
validateChallenge: (req, res, next) => {
  // Check if request body, challengeID, done and code are present and have expected data types
  if (
    !req.body ||
    !req.body.challengeID ||
    !req.body.code ||
  ) {
    return res.status(400).send({
      msg: 'Please enter valid challenge params!', // Send error message if validation fails
  next(); // Call next middleware function if validation passes
Enter fullscreen mode Exit fullscreen mode

Now we take this code and pass it to ChatGPT with the following prompt: “Write tests for this code: CODE“.

With a single click, ChatGPT spits out a total of 5 test cases for our code.
ChatGPT generates JavaScript test cases for a Rest API<br>

If you already have other tests in your project you can of course tell ChatGPT to generate unit tests for a specific framework.

Overall, ChatGPT can help you work more efficiently and simplify the test writing process. So why not outsource this tedious task to an AI and optimize your development time?

💡 Tips when using ChatGPT

After using ChatGPT for quite a while now in my daily developer existence, I was able to find some tips & tricks when using ChatGPT.

1. Choose prompts correctly

To get good results you have to tell ChatGPT exactly what you want. Write 1-2 sentences more in the prompt, but you will usually get better results.

2. The correct IDE extensions

There are now numerous extensions available for all IDEs in marketplaces and stores. Just browse the stores. Since I personally use Visual Studio Code, I can only recommend the Genie extension for it.
Visual Studio Code: Genie Extension Beispiel<br>

3. Watch out for sensitive/secret data

Developers often deal with sensitive data, such as user information or secret company data. As a developer, it is therefore crucial to ensure that this data is not accidentally exposed when working with ChatGPT.

The best practice here is to provide only test data to ChatGPT. By making sure that no confidential information is used, you prevent accidental data leaks and keep your data safe.

4. ChatGPT works better with examples

Giving examples is an important step to improve the performance of ChatGPT. For example, if you ask ChatGPT to generate SQL queries or code, you will get better results if you provide concrete examples.

By providing a few lines of SQL code or the structure of the table, ChatGPT can better understand what you need and can provide more accurate results. Similarly, if you want ChatGPT to comment code. By providing sample comments, ChatGPT can better understand what you need and can generate more accurate comments.

5. Use English language

My native language is German, so it is easier for me to create German prompts. However, I have noticed that ChatGPT understands English prompts better and therefore gives better results. Pretty much all developer resources and documentation are in English, so ChatGPT naturally understands that better.

🐛 ChatGPT is not perfect – and makes mistakes!

Although ChatGPT is an impressive example of AI text generation, it still makes mistakes. One of the main limitations of ChatGPT is that it is based on data from 2021, which means it may use outdated technologies and frameworks. For this reason, it is important that developers carefully review the generated code before running it to ensure that it is correct and secure.

Another point to note is that ChatGPT cannot understand deep relationships between different programming technologies and concepts. It can generate code that is syntactically correct but may not have the desired functionality or efficiency. In such cases, it is important for the developer to use manual review and their own understanding of the underlying concepts and relationships to ensure that the generated code meets the requirements.

📍 Conclusion

In this day and age of technology and advancement, AI can be an incredibly valuable tool. ChatGPT, as one of the leading AI models, can help developers in a variety of ways – from developing code and scripts to writing tests and documentation.

Of course, there are a few things to keep in mind when using ChatGPT, like choosing the right prompts and IDE extensions, and avoiding sensitive data in prompts. But that shouldn’t stop us from taking full advantage of the power of AI!

Overall, ChatGPT is a useful assistant for any developer and can help save time and effort. However, if you rely too much on AI, there is a risk that you will be left like a fish out of water if the AI fails. Therefore, you should still have the necessary skills and knowledge to get the job done without ChatGPT.

So, dear developers, don’t be too scared to use ChatGPT, but don’t forget that all that glitters is not gold. And now let’s all get back to our work and look our new AI assistants in the eye with enthusiasm!

➡️ On my blog you can find many more tutorials and articles!

Do you already use ChatGPT in Development or what are your thoughts on ChatGPT? Let me know it in the comments! 😁

Thanks for reading! ❤️

And yes: ChatGPT helped me with this article too 😲

Top comments (2)

syeo66 profile image
Red Ochsenbein (he/him) • Edited

This article sounds very much like it was created using ChatGPT. You might want to review the guidelines.

webdeasy profile image

In fact, I have created some formulations with ChatGPT. Thanks for the hint, I did not knew the new guidelines and added an appropriate hint! ;)