How to Use ChatGPT Like a Developer 20 Prompts That Actually Work

How to Use ChatGPT Like a Developer: 20 Prompts That Actually Work

ChatGPT, when rightly used, can become a powerful tool to assist developers during studies and coding sessions. This speeds up logical reasoning, reduces debugging time, automates tasks, aids in code auditing, and provides ideas on how to code better and understand projects. But, to use its power to the full extent, you must understand how to properly use this tool and take maximum advantage of its powers. Stay tuned and learn more about how to do it in this article!

Why Developers Should Learn to Use ChatGPT Effectively

The implementation of AI tools such as ChatGPT into every aspect of the modern software development process isn’t an idea for the future, but a current reality. Every developer should, at this point, be a master of at least the basic principles of how to use artificial intelligence, how to properly write a well-made prompt, and how to get it to do exactly what you need. And, if you don’t take your time to learn it, then you are already missing out on one of the most important innovations in the IT industry, especially one that we are sure isn’t going anywhere any time soon. This means that, yes, artificial intelligence is already part of everyday software development, and it is only going to take more and more space in the developers’ lives.

Still, this “obligation” is by no means some made-up marketing play or something like that. On the contrary, Artificial Intelligence tools are extremely powerful and useful, and can automate very complex tasks, help you understand old code, debug existing code, help you generate new ones, etc. All of this can help you save lots of time and effort, making your thought process less painful and potentially saving hours of work in tasks you don’t like that much, such as documenting, reading docs, among others. So, when you know how to use AI to your advantage properly, it’s an absolute win-win situation, and there’s no reason not to use it.

Still, as we will discuss further, there are some dangers in getting assistance from artificial intelligence tools when you don’t actually master them. For instance, they always try to please and to be polite and positive, which means that they will agree with you even when you’re wrong, and then give wrong results just to please you. Additionally, its knowledge is limited, most notably when it is tested under new circumstances or with things it has never encountered before, situations in which it will almost surely fail and hallucinate. That’s really dangerous, as the AI model doesn’t admit its ignorance, while speaking with full confidence and making you think it’s right. So it’s crucial to understand how these models work, how they think, what they can and cannot do, etc.

Understanding the Developer Mindset in ChatGPT Prompts

To use ChatGPT as the powerful tool it is to assist in the development process, you must first think like a developer and understand how to make it think like you want it to. That’s especially important with AI chatbots, as they always try to please and give positive responses and reviews, even when something’s wrong, either in your code or in your line of thought. Also, it sometimes might become too loose on its ideas, churning out lots of text, which only makes the situation more complex to understand; so, you must know how to make it more succinct and avoid talking nonsense.

So, you must bear in mind that, sometimes, writing a good prompt is somewhat like coding, too. You must be extremely precise and strict, writing exactly what you need, how your input is going to be, and what you expect as output, etc. It will drastically reduce the chances of hallucinations from the AI chatbot, and your results will be much more precise. Sometimes, it is the difference between wasting a lot of time in failed attempts to get the proper results from ChatGPT. So, here are some examples of the difference between good and bad prompts:

  1.  Bad prompt: I’m creating a web software with Prisma and must create a login function. help me

    This prompt will lead ChatGPT to provide a comprehensive response covering everything related to a login function, from its working principles to the actual Prisma models, the dependencies to be installed, and, finally, the Node.js code. It definitely has a lot of noise and will lead to even a bigger mind effort to understand everything than just straight-up writing the code.

    Good prompt: I’m writing the back-end for a web service with NestJS and Prisma connected to a MySQL database, and, at the moment, I need help writing an authentication process. Help me with it. Let’s start by creating the models.

    This will return a much more concise and straightforward text, as the AI model will actually understand all of your context and have a specified scope, which is to create only the models. It may also suggest next steps in an easy and concise way, without writing tons of text to confuse you.
  2. Bad prompt: Fix this bug: (pastes the code)

    As usual, you must always fill your prompt with as much context as possible. Sometimes, the trace of the error might be enough to get it fixed, but most of the time, you really should give it a lot of details, writing a rich prompt that allows it to understand the bigger picture.

    Good prompt: This is the code to the login button of my frontend project made with VueJS: (pastes the code). It is returning an error, even though the API response is alright, and I can’t find out why. Please help me.

    This gives context to ChatGPT and lets it understand the bigger picture, see what’s actually happening, and comprehend what might be causing the bug. With this, the response will be much more precise and will very probably fix the bug on the first try.

Those are some basic examples, but they can already explain the importance of being as precise and concise as possible, in order to get the best results as soon as possible.

The 3 Golden Rules for Writing Developer Prompts

There are some golden rules for better writing prompts, so much so that this practice is called prompt engineering. So, to elucidate it, in this section, we provide you with a few quick tips on how to utilize language models to their maximum potential, assisting you during your development, and making sure you get the best results. So, here are a few tips on how to do it:

  • Be specific and straightforward: The first and most important rule for using artificial intelligence tools is to be as specific as possible, stating your necessities explicitly and clearly. This comes to make sure the LLM doesn’t fabricate something new, misinterpret your prompt, or hallucinate by not understanding exactly what you need. 
  • Include context: The LLM should understand and know what you’re speaking of to assist you. If you’re writing code, say what your language and framework are, how you want your code to be, what your goal is, etc. If, on the other hand, you’re trying to fix bugs, then you must brief it into your codebase, that is, what it does, the classes, show your error trace, explain what you want to happen, etc. With it, the artificial intelligence model will gain a broader perspective and understand your context and what’s happening, thus assisting you with its full capabilities.
  • Ask for explanations: You must ask the artificial intelligence to explain whatever it does with your codebase. That’s because it very frequently hallucinates and misinterprets you, or sometimes it doesn’t even understand your code, what it does, and what it should do. By asking for explanations, you both force the model to think a little bit harder and also get an in-depth guide of what it did and how it did it, and then you can judge whether or not what it suggests makes sense.

By following these rules, you’ll gather much more trustworthy results from your AI experience and actually use it to its full potential. Doing this is crucial to ensure you’re not wasting time trying to get concise answers from the AI agents, as it “cuts the evil from its roots”, avoiding hallucination from the beginning.

20 ChatGPT Prompts That Actually Work for Developers

Now, to help you actually implement this new “framework” for speaking with ChatGPT, here are 20 different prompts that actually work and speed up the development process:

Code Generation and Refactoring

  • Generate a full function from a requirement: Write a JavaScript function that receives a list of users and returns those who are over 18 years old. Don’t add comments; make it inline.
  • Refactor old code into a cleaner version: Refactor the following Python code to follow PEP8 standards and remove redundant loops. The logic must stay identical:
result = [] 

for i in range(len(items)): 

   if items[i] not in result: 

       result.append(items[i])
  • Generate reusable code components: Create a reusable React component for a button that accepts color, label, and onClick props. Use TypeScript and Tailwind CSS.
  • Convert between languages: Convert this Node.js Express route into a Python Flask equivalent, maintaining the same API behavior and response format:
    app.get('/users/:id', async (req, res) => { 
    
       const user = await db.findById(req.params.id); 
    
       res.json(user); 
    
     });
    • Generate boilerplate for a new feature: Generate the initial boilerplate for a NestJS module named “Report”. Include controller, service, and DTO files with TypeScript decorators.

    Debugging and Error Explanation

    • Explain an unknown error: Explain this error in simple terms and tell me what probably caused it:
    TypeError: Cannot read properties of undefined (reading 'map') 
    
       at renderUsers (App.js:42:12) 
    
       at App (App.js:10:3)
    • Diagnose complex stack traces: Analyze this Python error, tell me which part of the code caused it, and how to fix:
    Traceback (most recent call last):
    
     File "main.py", line 45, in <module>
    
       total = calculate_total(prices)
    
     File "main.py", line 22, in calculate_total
    
       return sum(price['value'] for price in prices)
    
    TypeError: 'int' object is not subscriptable
    • Find performance bottlenecks: This code runs much slower than expected. Analyze it and tell me where the inefficient part is, and suggest a more performant alternative. 
    const result = [];
    
    for (let i = 0; i < items.length; i++) {
    
     if (!result.includes(items[i])) result.push(items[i]);
    
    }
    • Debug with context and dependencies: I’m using Prisma with NestJS, and I’m getting this error:
      PrismaClientInitializationError: Can’t reach database server at localhost:5432
      Here’s my schema.prisma and .env files. Can you identify the problem?

    Documentation and Code Comments

    • Generate Python docstrings automatically: Add PEP257-style docstrings to this Python class:
    class User:
    
       def __init__(self, name, age):
    
           self.name = name
    
           self.age = age
    
      
    
       def greet(self):
    
           return f'Hello, {self.name}!'
    • Generate API documentation from code: Generate a short API documentation in markdown format for the following Express.js routes:
    app.get('/users', getUsers);
    
    app.post('/users', createUser);
    
    app.delete('/users/:id', deleteUser);
    • Explain code behavior: Explain this function step by step as if you were writing documentation for a non-technical stakeholder:
    export function calculateTax(amount: number, rate: number): number {
    
       return amount * rate;
    
     }

    Learning New Frameworks or APIs

    • Quick start guide for a framework: Explain how to get started with NestJS. Bear in mind that I already have experience with Express.js. Include folder structure and an example of a controller, service, and module.
    • Example usage of a specific API method: Show examples of using React’s useEffect hook for different contexts: fetching data, updating the document title, and subscribing to a WebSocket.
    • Compare two frameworks or libraries: What’s best for building REST APIs with Python: Django or Flask? Include advantages, disadvantages, when to choose each, and which is more popular nowadays.
    • Explain advanced concepts simply: Explain React Context API and how to replace Redux with it in a small project. Provide a simple code example.

          Productivity and Workflow Automation

          • Review pull request code automatically: Review the following pull request code and suggest improvements for readability, best practices, and potential bugs. Comment as if you were a senior software developer:
          function calculateTotal(items) { 
          
             let total = 0; 
          
             for (let i = 0; i < items.length; i++) { 
          
               total += items[i].price; 
          
             } 
          
             return total; 
          
           } 
          • Generate automation scripts: Create a Bash script that will run on Ubuntu and that backs up a folder called “projects” to Google Drive daily at 2 AM, and logs the result into a file called backup.log.
          • Generate boilerplate for routine tasks: Create a Python script template that fetches data from a REST API, processes it, and saves results to a CSV. Include error handling and logging.
          • Auto-generate GitHub issues from a todo list: I have the following project todo list:
            – Implement login
            – Add user profile page
            – Fix bug with password reset
            – Write tests for endpoints
            Generate GitHub issues for each item, with titles, descriptions, and labels like feature or bug.

          Conclusion: The Developer’s Competitive Edge with ChatGPT

          In the contemporary software development process, implementing AI is no longer an important competitive advantage: it is actually expected from the developer, and he should do it to keep going with new trends. It is already commonplace to use such assistance while developing, and some IDEs even have artificial intelligence models embedded directly into them. It also reduces costs, both by saving your time and preventing costly mistakes that could go into production, and will improve your productivity by assisting you in writing boilerplate code, reducing mental strain, among others. 

          But, to properly extract what ChatGPT is actually capable of providing, you must master how to use it, how to properly write a prompt, and how to get it to do what you want it to do. From this, derive some really important rules: always be specific and straightforward, provide context, and ask for step-by-step guides.  And, to better illustrate these rules, we have provided you with 20 wonderful AI prompts to assist you in understanding how to properly use artificial intelligence tools. Start using these prompts today and code smarter!

          FAQ – ChatGPT for Developers

          What are the best ChatGPT prompts for developers?
          From the twenty prompts we have cited previously, some stand out as the most useful daily, as they are more commonly used and fix everyday activities quickly and reliably. And, in that context, “Refactor old code into a cleaner version”, “Explain code behavior”, and “Explain an unknown error” stand out as the most used on a day-to-day basis. They usually come in handy in the most mentally complex tasks, those that tend to take the most time to be completed, and have a higher chance of generating more bugs and errors.

          Can ChatGPT replace developers?
          That’s a matter that has been debated many times over, but from the beginning, it has had a definite answer. While it is true that ChatGPT and other artificial intelligence tools can automate much of the development process and sometimes understand codebases better than actual developers, it will always be a tool. This means that, as powerful as it is, there must be an intelligent mind behind the decision process; that is, someone must at least tell the AI what to do, how to do it, and judge whether or not it’s done. And that person, by definition, is the developer: even if the programming language turns out to be natural language, this person is still somehow the developer.

          How can I use ChatGPT for code debugging?
          ChatGPT can assist in almost every step of code debugging, making it a very useful tool to assist in this usually boring and tiresome process. Therefore, there are some quick tips on how ot use it for assistance in debugging. First of all, you must gather as much detail and information as possible on your bug: the overall context of your application, the exact piece of code that is most probably glitching, the error stack trace, etc. Then you must aggregate it all in a well-structured prompt to help ChatGPT understand the whole context, and ask it to explain its thought process step by step before providing an answer. Then, after careful review, you must judge whether or not the response makes sense and is going to help; always remember: in the end of the day, the decision is up to you to take, and you’re the one piloting the AI model.