15 Prompts for ChatGPT and GPT-4: Programming, Debugging, Refactoring

15 Prompts for ChatGPT and GPT-4: Programming, Debugging, Refactoring

Introduction

If you write code daily, you've likely noticed that Generative AI is no longer a novelty — it's a core productivity tool. GPT-4, in particular, excels at generating boilerplate, spotting bugs, and suggesting architectural improvements. But the magic isn't just in the model; it's in how you talk to it. A vague prompt yields a vague answer. A precise, structured prompt can save you hours.

In this guide, I'll share 15 battle-tested prompts I use in my own workflow — from writing microservices to cleaning up legacy spaghetti. Each prompt comes with a real-world example and a brief explanation of why it works. No fluff, just practical value.

1. Generate a Function with Full Type Annotations

Prompt:

"Write a Python function validate_email(email: str) -> bool that checks if the email matches a standard pattern. Include docstring, edge cases (empty string, missing @, invalid domain), and use the re module. Return True for valid, False otherwise."

Why it works: Specifying the signature, library, edge cases, and return type eliminates ambiguity. GPT-4 outputs production-ready code, not a stub.

Example output (condensed):

import re

def validate_email(email: str) -> bool:
    """Validate email format.

    Args:
        email: String to validate.

    Returns:
        True if email matches standard pattern, False otherwise.
    """
    if not email:
        return False
    pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
    return bool(re.match(pattern, email))

2. Debug with Context and Expectations

Prompt:

"I have this Python code that raises KeyError randomly. Here's the function: [paste code]. The error occurs when processing user data from a JSON file. Expected behavior: it should return a default value if the key is missing. Find the bug and fix it. Suggest both immediate fix and long-term improvement."

Why it works: Giving the error type, context, and expected outcome focuses GPT-4 on your specific scenario instead of generic debugging.

3. Refactor Legacy Code for Readability

Prompt:

"Refactor this JavaScript function that calculates order totals. It's 200 lines long, uses nested callbacks, and has no comments. Requirements: (1) convert to async/await, (2) extract discount logic into a separate pure function, (3) add JSDoc comments. Keep the same external API."

Real outcome: GPT-4 typically reduces line count by 40-50% and adds meaningful names for helper functions.

4. Generate Unit Tests with Coverage in Mind

Prompt:

"Write pytest unit tests for the validate_email function from prompt #1. Include tests for: valid email, invalid email (no @), empty string, string with spaces, and a domain with subdomain. Use parametrized tests. Ensure 100% branch coverage."

Why it matters: Explicitly asking for branch coverage nudges GPT-4 to write more thorough tests than the default happy-path examples.

5. Explain a Complex Code Block

Prompt:

"Explain this Rust function that uses std::sync::Arc and tokio::spawn. I'm an intermediate Python developer. Focus on: why Arc is needed here, how ownership works, and the role of tokio in concurrency. Use analogies."

Why it works: Specifying your background and preferred explanation style (analogies) makes the output much more useful than a dry reference.

6. Design a REST API Endpoint

Prompt:

"Design a REST API endpoint for creating a user in a FastAPI app. Requirements: (1) accepts JSON with email and password, (2) validates email format, (3) hashes password with bcrypt, (4) returns 201 with user ID. Include request/response examples and error handling for duplicate email."

Bonus: Add "Use pydantic for validation and sqlalchemy for DB" to lock in the tech stack.

7. Optimize a Slow SQL Query

Prompt:

"This query takes 12 seconds on a table with 5 million rows. [paste query]. The WHERE clause uses LIKE '%keyword%'. Suggest indexing strategy and query rewrite to reduce execution time to under 1 second. Explain trade-offs."

Why it's effective: GPT-4 can identify missing indexes, recommend full-text search (e.g., PostgreSQL tsvector), and warn about over-indexing.

8. Generate API Client Stubs

Prompt:

"Generate a Python client class for the Stripe API's payment intents endpoint. Include methods: create, retrieve, update, list. Use requests library. Add retry logic with exponential backoff. Handle rate limiting (429) responses."

Real use case: I used this prompt to build a test harness for integrating Stripe payments into an e-commerce prototype. ASI Biont supports connecting to Stripe through its API — for more details, visit asibiont.com/courses. The generated client saved about 3 hours of boilerplate.

9. Write a Dockerfile for a Python App

Prompt:

"Write a Dockerfile for a Python 3.12 FastAPI app. Requirements: multi-stage build, use uv for dependency management, expose port 8000, run as non-root user, include health check. Keep image size under 200 MB."

Why it works: With multi-stage and uv, GPT-4 typically produces images around 150-180 MB, compared to 400+ MB with naive pip install.

10. Explain a Design Pattern

Prompt:

"Explain the Strategy Pattern in TypeScript with a real-world example: a shopping cart that calculates shipping costs based on different carriers (UPS, FedEx, USPS). Show interface, concrete strategies, and context class. Include a usage example."

Why it's useful: Concrete examples beat abstract definitions every time.

11. Generate Configuration Files

Prompt:

"Generate a .gitlab-ci.yml file for a Python project. Stages: test, build, deploy. Use python:3.12-slim image, run pytest with coverage, build Docker image only on main branch, deploy to AWS ECS."

Real outcome: GPT-4 produces a working YAML with proper artifacts, caching, and environment variables.

12. Write a Migration Script

Prompt:

"Write an Alembic migration script to add a last_login column (datetime, nullable) to the users table, and populate it with existing created_at values. Use PostgreSQL dialect. Include upgrade and downgrade functions."

Why it's safe: GPT-4 generates reversible migrations that respect database constraints.

13. Generate Documentation for an API

Prompt:

"Write OpenAPI 3.0 specification for a simple CRUD API managing books. Include endpoints: GET /books, POST /books, GET /books/{id}, DELETE /books/{id}. Use proper response codes, request bodies, and error schema."

Why it matters: GPT-4 can output valid YAML that you can directly import into Swagger UI.

14. Create a Boilerplate for a New Microservice

Prompt:

"Generate a complete project structure for a Go microservice. Include: main.go with HTTP server, handlers directory, models, database connection (PostgreSQL), Dockerfile, and Makefile. Use gorilla/mux for routing and pgx for DB."

Time saved: Approximately 2-3 hours of repetitive setup.

15. Review Code for Security Vulnerabilities

Prompt:

"Review this Python code for security issues. [paste code]. Look for: SQL injection, XSS, hardcoded secrets, insecure deserialization, and missing input validation. For each issue, explain the risk and provide a fix."

Why it's critical: GPT-4 catches common OWASP Top 10 issues that even experienced developers might miss in a rush.

Conclusion

These 15 prompts aren't theoretical — they've been refined through months of daily use. The common thread is specificity: the more context you give GPT-4 about your language, framework, constraints, and expected outcome, the more useful the output becomes.

Start by copy-pasting these prompts into your next session. Adjust the tech stack and requirements to match your project. Within a few tries, you'll see that GPT-4 becomes less of a "magic box" and more of a reliable pair programmer — one that never gets tired of writing boilerplate or reviewing edge cases.

Happy prompting.

← All posts

Comments