AI

How to prompt AI to write better code

Avi, the Avenux Techspire mascot, illustrating: How to prompt AI to write better code

When a student tells me “the AI gave me rubbish code”, I ask to see the prompt. Most of the time it is one line, something like “make a login page”. The assistant has no idea what language, framework, database, styling or rules you have in mind, so it guesses. And guesses are generic.

Getting better code from an AI assistant is less about secret tricks and more about being clear, the same way you would brief a new teammate.

1. Give it context

The assistant cannot see your project unless you show it, or unless the tool you use is reading your files. Tell it the basics up front:

  • Language and version (PHP 8, Python 3, Dart with null safety)
  • Framework and libraries (Laravel, Express, Flutter with Provider)
  • Where this code fits (a controller, a React component, a utility function)
  • Anything already decided (we use MySQL, we use Tailwind, we use fetch, not axios)

Compare these two prompts.

Bad:
Write a function to validate a form.

Better:
I'm using plain JavaScript in the browser, no libraries.
Write a function validateSignup(form) that checks:
- name is not empty
- email looks like an email
- password is at least 8 characters
Return an object like { valid: boolean, errors: { field: message } }.
Don't touch the DOM inside the function.

The second prompt takes thirty seconds longer to write and saves you ten minutes of fixing.

2. State your constraints

Constraints are where the real quality comes from. Things worth spelling out:

  • “Use prepared statements, no string concatenation in SQL.”
  • “Must work without any new dependencies.”
  • “Keep it under 40 lines, readable over clever.”
  • “Handle the empty list case and network errors.”
  • “Follow the naming style in the code I pasted below.”

If you do not mention error handling, you often will not get it. If you do not mention security, the assistant may write something that works but is unsafe.

3. Show examples

Paste a small sample of your existing code, or an example of the input and expected output. Examples remove ambiguity faster than any amount of description.

Input:  "  Hello   World  "
Output: "hello-world"

Write a slugify(text) function in Python that matches this.
Also handle accented letters and remove anything that isn't a-z, 0-9 or a hyphen.

When you show the assistant your existing patterns, its output fits into your project instead of looking like it came from a different codebase.

4. Ask for small pieces

“Build me a complete e-commerce site” will give you a lot of code you cannot review properly. Break it down:

  1. “Design the database tables for products, carts and orders. Just the schema, explain each column.”
  2. “Now write the function to add an item to the cart.”
  3. “Now write tests for that function.”

Small steps are easier to check, easier to fix and easier to understand. You also stay in charge of the overall design, which is your job, not the assistant’s.

5. Ask it to plan before coding

For anything non-trivial, ask for an approach first:

Before writing any code, list the steps you'd take to add
pagination to this API endpoint, and any questions you have
about my requirements.

This often surfaces wrong assumptions early. You correct the plan in two lines instead of correcting a hundred lines of code.

6. Tell it what is wrong, specifically

When the first answer is not right, “this doesn’t work” is not useful feedback. Share the actual error message, what you expected, and what happened instead:

Running this gives:
TypeError: Cannot read properties of undefined (reading 'map')
at line 12. The API sometimes returns { items: null }.
Update the function to handle that.

Specific feedback gets specific fixes.

7. Ask it to explain and to criticise

Two prompts I use a lot after getting code:

  • “Explain this code line by line as if I’m a beginner.”
  • “What are the weaknesses or edge cases in this code? What would break it?”

The second one is surprisingly effective. An assistant will often point out problems in its own answer that it did not mention the first time.

8. Start a fresh chat when it gets messy

Long conversations with many changes of direction tend to produce confused answers, where the assistant mixes old and new requirements. If that happens, open a new chat, paste the current version of your code and a clean summary of what you need. It feels like starting over, but it usually works better.

What good prompting does not replace

Even a perfect prompt can produce code that calls a function that does not exist, or uses an old version of a library. Always:

  • Run it and test it, including with bad inputs.
  • Check unfamiliar functions in the official documentation.
  • Read it fully before committing. You are the one responsible for it.

Prompting well is a real skill, and it is closely tied to knowing how to program. The better you understand the problem and the tools, the better your prompts get. That is why learning fundamentals still matters, even with AI in the picture.

A simple template

If you want a starting point, this structure covers most coding requests:

Context: [language, framework, where this code lives]
Task: [what you want, one clear sentence]
Requirements:
- [rule 1]
- [rule 2]
Example: [input and expected output, or existing code style]
Output: [just the function / full file / explanation first]

Fill it in honestly and you will notice the difference straight away.