AI coding assistants such as GitHub Copilot, ChatGPT, Claude, Gemini, Cursor and others can explain unfamiliar code, draft functions, write tests, suggest fixes and document systems. Used well, they speed up routine work and help developers learn. Used carelessly, they produce code that looks right but has subtle bugs, security problems or licence issues.
Coding prompts are most useful when they include the environment, acceptance criteria, constraints and a small reproducible example. They should improve review, not bypass it. This guide gives you a reusable prompt pattern and ready-to-adapt prompts for understanding code, implementing features, debugging, testing, refactoring, reviewing, documenting and working with databases and spreadsheets, plus rules for using AI safely with business code.
Key takeaways
- Describe the current behaviour and desired change, and list versions, files and interfaces.
- Provide a minimal failing example when debugging.
- Ask for tests, edge cases and rollback notes alongside code.
- Review every patch and run it in a safe environment before deployment.
- Never paste secrets, credentials or production data into an unapproved tool.
- Check dependencies, permissions, error handling and security before deployment.
A reusable coding prompt pattern
- Context: language, framework, versions, runtime and relevant files or interfaces.
- Current behaviour: what the code does now, including errors.
- Desired behaviour: what it should do, written as acceptance criteria.
- Constraints: style conventions, libraries allowed or not allowed, performance limits, backward compatibility.
- Example: a minimal input and expected output, or a failing test.
- Output request: the code change, tests, explanation of trade-offs and any risks or rollback notes.
Example: “We use Python 3.12 with Django 5. The invoice export view times out for customers with more than 5,000 invoices. It should stream a CSV without loading all records into memory, keep the same column order and headers, and include tests. Do not add new third-party dependencies. Here is the current view and model: [paste]. Explain any trade-offs and what to monitor after deployment.”
Prompts for understanding code
Explain unfamiliar code
“Explain what this function does, step by step, for a developer new to this codebase. Identify inputs, outputs, side effects, external calls and any assumptions or risks you notice. Code: [paste].”
Map a module
“Here are the files in our billing module. Summarize how they fit together, the main data flow, where external services are called and which parts look fragile or hard to test.”
Explain an error
“Explain this error message and stack trace in plain language, list the most likely causes in order of probability and suggest how to confirm each one. Environment: Node 20, Express 4. Error: [paste].”
Prompts for implementing features
Write a function with acceptance criteria
“Write a TypeScript function that validates Canadian postal codes and US ZIP codes. Acceptance criteria: accepts ‘A1A 1A1’ and ‘A1A1A1’, accepts five-digit and ZIP+4 formats, rejects other formats, returns a normalized string. Include unit tests with edge cases and explain any limitations.”
Add a feature to existing code
“Add pagination to this API endpoint. Use cursor-based pagination with a default page size of 50 and a maximum of 200. Keep the response format backward compatible by adding a next_cursor field. Update tests. Current code: [paste].”
Integrate an API
“Write a minimal client for this REST API using the documentation excerpt below. Handle authentication via an API key read from environment variables, retries with exponential backoff for 429 and 5xx responses, and clear error messages. Do not hard-code secrets.”
Prompts for debugging
Provide a minimal failing example
“This function should return the total including tax, but for the input below it returns 112.99999 instead of 113.00. Here is the function, the input and the expected output. Explain the cause and suggest a fix that handles currency correctly. Python 3.11.”
Narrow down a problem
“Our React form submits twice when the user presses Enter. Here is the component and the parent. Suggest a step-by-step debugging plan, list likely causes and propose a fix with a test.”
Investigate performance
“This SQL query takes eight seconds on a table with two million rows. Here is the query, the table schema and the existing indexes. Explain why it is slow and suggest improvements, including any index changes and their trade-offs for write performance.”
Prompts for tests
Write tests for existing code
“Write unit tests for this function using pytest. Cover normal cases, boundary values, invalid input and error handling. Do not change the function. List any behaviours that seem like bugs.”
Find edge cases
“List edge cases this date-handling function might fail on, including time zones, daylight saving changes, leap years and different locale formats. Then write tests for the five most important.”
Turn a bug report into a regression test
“Based on this bug report, write a failing test that reproduces the issue, then propose the minimal fix that makes it pass.”
Prompts for refactoring
“Refactor this function to improve readability and testability without changing behaviour. Keep the public interface the same, explain each change and provide tests that confirm behaviour is unchanged.”
“Identify duplicated logic across these three files and suggest a shared helper. Show the refactored code and note any risks.”
Prompts for code review
“Review this pull request diff as a senior engineer. Look for bugs, security issues, missing error handling, performance problems, unclear naming and missing tests. Prioritize findings by severity and explain each one briefly.”
“Check this code for common security issues, including injection, cross-site scripting, insecure deserialization, missing authorization checks and secrets in code. Suggest specific fixes.”
Prompts for documentation
“Write a README section explaining how to set up this project locally, including prerequisites, environment variables (names only, no values), setup commands and how to run tests.”
“Write docstrings for these functions following our style: one-line summary, parameters, return value, exceptions raised and an example.”
“Create a short runbook for this background job: what it does, schedule, dependencies, common failures and how to recover.”
Prompts for databases, scripts and spreadsheets
“Write a SQL query that returns monthly revenue by customer for the last 12 months from these tables. Include customers with no revenue as zero. Explain the joins.”
“Write a Google Sheets formula that looks up a customer’s account manager from another tab by customer ID and returns ‘Unassigned’ if not found.”
“Write a small Python script that reads a CSV of contacts, removes duplicates by email (case-insensitive), standardizes phone numbers to E.164 format for Canada and the US, and writes a cleaned file. Include error handling for missing columns.”
Prompts for planning and architecture
Compare implementation options
“We need to send appointment reminders by email and SMS for a clinic booking app built with Laravel. Compare three approaches: a scheduled job in the app, a queue-based worker and a third-party notification service. For each, explain complexity, cost drivers, reliability, privacy considerations and how it fails. Recommend one for a team of two developers.”
Design a data model
“Propose a database schema for tracking customer subscriptions with plan changes, cancellations, refunds and tax by province or state. Show tables, key fields and relationships, and explain how historical changes are preserved for reporting.”
Plan a migration
“We are moving from a monolithic PHP app to a separate API and front end. Suggest a phased migration plan that avoids downtime, lists risks for each phase and explains how to roll back.”
Prompts for DevOps and maintenance
“Write a GitHub Actions workflow that runs linting and tests on every pull request for a Node 20 project, caches dependencies and fails if test coverage drops below the current level. Use secrets only through the repository’s secret settings.”
“Review this Dockerfile for size, security and build speed. Suggest improvements such as multi-stage builds, non-root users and pinned base image versions.”
“Write a checklist for upgrading this application from one major framework version to the next, including dependency checks, breaking changes to review, test plans and rollback steps.”
Prompts for learning
“Teach me how async and await work in JavaScript using this example from our codebase. Start simple, then explain common mistakes and how to test async code.”
“Quiz me with five questions about SQL joins based on our schema, then explain the answers.”
Learning prompts are one of the most valuable uses of AI for junior developers, because they build understanding rather than just producing code.
Prompts for accessibility and front-end quality
“Review this React component for accessibility issues against WCAG 2.1 AA, including labels, keyboard navigation, focus management, colour contrast and screen reader announcements. Suggest specific code changes.”
“Make this form accessible: add proper labels, error messages linked to fields, and keyboard support. Keep the existing styling.”
Working iteratively with AI
Good results usually come from a conversation, not one prompt:
- Ask for a plan before code: “Outline your approach and the files you would change. Do not write code yet.”
- Review the plan and correct misunderstandings.
- Ask for the implementation in small steps.
- Run tests and share failures: “Test X fails with this output. Fix the cause, not the test.”
- Ask for a final review: “What could go wrong with this change in production?”
For agentic coding tools that can edit files and run commands, keep tasks small, review diffs carefully and use version control so changes can be reverted.
Review the patch and run it safely
AI-generated code must be reviewed like any other contribution. Before merging:
- Read every line: understand what the code does and why.
- Run tests locally or in CI: including new tests for the change.
- Use a safe environment: test in development or staging, never directly in production.
- Check edge cases: empty inputs, large inputs, invalid data and concurrency.
- Check error handling: failures should be logged clearly and handled gracefully.
- Check performance: especially database queries and loops over large data sets.
Security and privacy rules
Never paste secrets or production data into unapproved tools
API keys, passwords, tokens, private keys, connection strings and customer data must never be pasted into AI tools that your organization has not approved for that use. Replace secrets with placeholders and use synthetic or anonymized data for examples. If a secret is exposed, rotate it immediately.
Check dependencies
AI may suggest packages that are outdated, vulnerable, unmaintained or even nonexistent. Attackers have published malicious packages with names that AI tools tend to invent. Verify every dependency on its official registry, check its maintenance and licence, and use dependency scanning tools.
Check permissions and access control
Make sure generated code enforces authentication and authorization correctly, follows the principle of least privilege and does not expose internal data through APIs or logs.
Check licences
AI output may resemble existing code. Follow your organization’s policy on licence compliance, and use tools’ features for filtering suggestions that match public code where available.
Protect personal information
Code that processes personal information must comply with privacy laws such as PIPEDA and Quebec’s Law 25 in Canada and applicable US state and sector laws. Ask AI to help implement data minimization, encryption and retention rules, but verify the implementation.
Choosing approved tools
Business and enterprise versions of AI coding tools typically offer stronger data protections, such as not training on your code, admin controls and audit logs. Work with your team to approve specific tools, configure settings and document what code and data may be shared. See our guide to the best AI coding tools.
Prompts for non-developers
Business users increasingly use AI to build small scripts, spreadsheet automations and prototypes. These prompts work well when you describe the goal in plain language:
“I’m not a developer. I have a Google Sheet with orders in columns A to F. Write a Google Apps Script that emails me a summary every Monday of orders over $1,000 from the previous week. Explain step by step how to install and test it, and what permissions it will ask for.”
“Explain what this Zapier code step does in simple terms and whether it handles errors. Suggest improvements.”
For anything that touches customer data, payments or business-critical systems, have a developer review AI-generated code before using it. See our guide on AI-built prototypes versus production apps.
Building a team prompt library
Save prompts that work well in a shared document or repository, with the context they need and notes on review. Useful entries include code review checklists, test generation templates, documentation formats and debugging plans. Include your coding standards and architecture notes so AI suggestions match your conventions.
Common mistakes to avoid
- Vague prompts: “Fix my code” without context produces guesses.
- Accepting code without understanding it: you are responsible for what you merge.
- Skipping tests: ask for tests and run them.
- Pasting secrets or customer data: use placeholders and synthetic data.
- Trusting suggested packages blindly: verify every dependency.
- Letting AI change tests to pass: fix causes, not symptoms.
- Large, unreviewed changes: keep changes small and reviewable.
The bottom line
Effective coding prompts include the environment, current and desired behaviour, constraints, a minimal example and a request for tests and risks. Use AI to understand code, implement features, debug, test, refactor, review and document, but treat its output as a draft. Review every patch, run it in a safe environment, verify dependencies and security, and never paste secrets or production data into unapproved tools.
FAQs
What makes a good coding prompt?
Clear context (language, versions, files), current and desired behaviour, constraints, a minimal example and a request for tests and explanations.
Can AI write production-ready code?
AI can produce useful code, but it must be reviewed, tested and secured by someone who understands it before reaching production.
Is it safe to paste my code into AI tools?
Use tools your organization has approved, with appropriate data protections. Never paste secrets, credentials or personal data.
How do I get AI to follow our coding style?
Include your style guide or examples in the prompt, or configure project instructions in tools that support them.
Which AI coding tool is best?
It depends on your editor, languages, workflow and policies. Many teams use an editor-integrated assistant plus a chat assistant for explanations and planning.
Can AI help with legacy code?
Yes. AI is useful for explaining old code, writing characterization tests before changes and suggesting incremental refactors. Move in small steps and keep tests passing.
Should junior developers use AI coding tools?
Yes, with guidance. Encourage them to ask for explanations, write code themselves first and use AI for review and learning, so they build real understanding.
How do I stop AI from inventing functions or APIs?
Provide the actual documentation, interfaces or code you are working with, ask it to use only what is shown, and tell it to say when something is unknown. Always run the code to confirm.
Can AI write database migrations safely?
AI can draft migrations, but review them carefully, test on a copy of the database and plan a rollback before running anything in production.
Sources and further reading
- OWASP Top 10
- OWASP Top 10 for LLM Applications
- CISA: Secure by Design
- Canadian Centre for Cyber Security
