Welcome to EasyCodingWithAI!

Before you dive into coding with AI, take a moment to consider some valuable insights.

Our articles cover the pros and cons of using AI in development, the importance of having a development environment, and how AI empowers hobbyists and small businesses to create and maintain their own websites, without the need of hiring professional developers.

Richard Robins

Article : Building Better Prompts: The Art of Communicating with AI for Coding

Posted by Richard Robins on January 1, 2025.

AI tools like ChatGPT and GitHub Copilot have revolutionized the way developers approach coding tasks. By offering instant solutions, debugging help, and even writing entire functions, these tools can dramatically improve productivity.

However, the quality and relevance of the code generated depend heavily on the clarity and specificity of the prompts you give them. Just as with any form of communication, the more precise and detailed your instructions, the better the results will be.

Crafting effective prompts is an essential skill for developers looking to maximize the potential of AI coding assistants. This article explores practical tips for building better prompts to get the most accurate, relevant, and useful code from AI.


1. Be Specific About Your Requirements

One of the most common mistakes when using AI tools is providing overly vague or broad prompts. AI tools rely on patterns in the data they’ve been trained on, and when faced with unclear instructions, they can generate generic or imprecise responses. To ensure that AI gives you the exact code you need, be as specific as possible about what you want.

Examples:

  • Instead of saying, “Create a function to sort a list,” try “Write a Python function that sorts a list of integers in ascending order using the quicksort algorithm.”
  • Instead of “Write a login page,” try “Generate HTML and CSS code for a login page with a username, password field, and a submit button. Include basic styling with centered form elements.”

Why This Works: By narrowing the scope of the task and providing clear details, you help the AI understand exactly what you’re asking for, leading to more targeted and useful code.


2. Include the Context of Your Project

When AI generates code, it typically doesn’t have access to the full context of your project, such as how the code interacts with other components, what libraries you are using, or the overall design patterns you’re following. Including relevant details about the context of your project can help the AI generate code that fits better with the existing structure.

Examples:

  • Instead of “Write a function to make an API request,” try “Write a Python function that uses the requests library to make a GET request to a public API and parses the JSON response into a Python dictionary.”
  • Instead of “Create a sorting algorithm,” try “Create a JavaScript function that sorts an array of objects based on a date field in descending order. The data is coming from an API response, so it will be in JSON format.”

Why This Works: By providing context, you enable the AI to consider the environment in which its code will be executed, which can lead to more efficient and seamless integration with your existing codebase.


3. State Your Constraints or Preferences

AI tools are great at offering solutions, but they might not always align with your preferences regarding performance, readability, or scalability. If you have specific constraints—such as using a particular library, adhering to best practices, or optimizing for performance—be sure to state them upfront.

Examples:

  • “Write a Python function to process large files. It should handle files up to 2GB in size and should not load the entire file into memory at once. Use memory-efficient techniques.”
  • “Generate a sorting function in JavaScript that should handle up to 10,000 items efficiently. Avoid using the built-in sort() method and implement a custom algorithm like quicksort.”

Why This Works: Setting expectations ensures that the generated code meets your project’s standards and is tailored to your specific needs, such as performance constraints or preferred methodologies.


4. Specify the Programming Language and Version

Different programming languages and even versions of those languages can have distinct syntax, features, and libraries. Be sure to specify the programming language you are using and, if relevant, the version, so the AI generates code that matches your environment.

Examples:

  • “Write a Python 3 function that converts a CSV file into a Pandas DataFrame.”
  • “Create a React component in JavaScript that displays a list of items. It should work in React 18.”

Why This Works: By being explicit about the language and version, you reduce the risk of getting incompatible code that may not work as expected in your environment.


5. Request Explanations or Comments

When you’re learning, debugging, or trying to understand a piece of code, having explanations or comments can be incredibly helpful. If you need clarification on how or why the code is structured a certain way, ask the AI to explain its approach or provide inline comments.

Examples:

  • “Generate a Python function to calculate Fibonacci numbers and include comments explaining each step.”
  • “Create a JavaScript function that merges two arrays and explain the use of concat() versus the spread operator.”

Why This Works: Asking for comments or explanations helps you understand the code, making it easier to modify, debug, or expand on. It also clarifies the AI’s logic, reducing confusion.


6. Break Down Large Tasks into Smaller Prompts

Instead of asking the AI to generate an entire program or application at once, break the task into smaller, manageable pieces. This approach will result in more focused and high-quality code, and you can piece it together as needed.

Examples:

  • Instead of “Create an e-commerce website,” break it into:
    • “Write a login form with email and password fields.”
    • “Generate a shopping cart function that calculates the total price.”
    • “Write a product listing page with pagination.”
  • Instead of “Create a machine learning model,” break it into:
    • “Generate Python code to preprocess the data for a machine learning model.”
    • “Write a function to train a logistic regression model using scikit-learn.”

Why This Works: Dividing the task allows you to get more focused answers for each individual part, which you can then combine to form the larger solution. It also helps the AI stay focused on one specific problem at a time.


7. Ask for Code Reviews or Improvements

Once AI generates code for you, consider asking it to review the code for potential errors, inefficiencies, or best practices. AI tools are great at spotting common issues or suggesting improvements.

Examples:

  • “Review the Python function I generated and suggest improvements for performance and readability.”
  • “Check the JavaScript code below and suggest any security improvements.”

Why This Works: Even though AI can generate code, it’s not infallible. Asking for a review helps identify potential issues, such as security flaws or performance bottlenecks, that might not have been immediately obvious.


8. Iterate and Refine Prompts Based on Results

Sometimes the first prompt you give an AI tool won’t result in the perfect code. Don’t be discouraged. Refine your prompt based on the output you receive. If the code doesn’t meet your expectations, provide feedback and ask the AI to adjust or rework certain parts.

Examples:

  • If the code generated doesn’t meet your performance requirements, you might say, “This solution is too slow. Can you optimize it to reduce the time complexity?”
  • If the AI’s suggestion isn’t flexible enough, you might say, “Can you refactor this function to accept dynamic input parameters instead of hard-coded values?”

Why This Works: Iteration allows you to fine-tune your prompts and the AI’s response. As you interact with the tool, you’ll get better results by refining both your instructions and your expectations.


9. Test the Code and Provide Feedback

After AI generates code, always test it thoroughly in your development environment. If you notice issues—such as errors, inefficiencies, or unexpected behavior—report these back to the AI tool (if it offers this feature) or refine your prompt to be more specific. This feedback loop helps improve the output quality over time.

Example:
After generating a piece of code, you might find an edge case where the solution doesn’t work correctly. You could refine your prompt: “The function fails when the input is an empty string. Can you adjust the logic to handle this case?”

Why This Works: Feedback and testing help you create a continuous improvement cycle where you learn to craft better prompts while helping the AI improve over time.


Conclusion

Effective communication with AI tools is key to getting the best results when generating code.

By being specific, providing context, setting clear constraints, and iterating on your prompts, you can ensure that the code generated is not only functional but also efficient, scalable, and aligned with your project’s goals. The more you understand the nuances of prompt engineering, the more you can harness the full potential of AI tools to enhance your development process.


Richard Robins

Richard Robins

Richard is passionate about sharing how AI resources such as ChatGPT and Microsoft Copilot can be used to create addons and write code, saving small website owners time and money, freeing them to focus on making their site a success.


Disclaimer

The coding tips and guides provided on this website are intended for informational and educational purposes only. While we strive to offer accurate and helpful content, these tips are meant as a starting point for your own coding projects and should not be considered professional advice.

We do not guarantee the effectiveness, security, or safety of any code or techniques discussed on this site. Implementing these tips is done at your own risk, and we encourage you to thoroughly test and evaluate any code before deploying it on your own website or application.

By using this site, you acknowledge that we are not responsible for any issues, damages, or losses that may arise from your use of the information provided herein.