Introduction
As of July 2026, GPT-4 and its successors have become indispensable tools for software engineers. Whether you're a junior developer struggling with a stubborn bug or a senior architect designing a microservices system, the right prompt can save hours of manual work. This article presents 18 carefully crafted prompts for ChatGPT and GPT-4, organized into three categories: basic (for beginners), advanced (for experienced developers), and expert (for architects and leads). Each prompt includes a task description, the exact prompt text, and a concrete example with real code. By the end, you'll have a reusable library of prompts that can boost your productivity, improve code quality, and help you tackle complex architectural decisions.
Basic Prompts
1. Generate a function from a description
Task: Ask GPT-4 to create a Python function that validates an email address using regex.
Prompt:
Write a Python function named `validate_email` that takes a string `email` as input and returns `True` if the email matches a standard pattern (e.g., contains '@' and a domain with a dot), otherwise returns `False`. Use a regular expression. Include a docstring and a simple test case.
Example result:
import re
def validate_email(email: str) -> bool:
"""Validate email using regex pattern."""
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return bool(re.match(pattern, email))
# Test case
print(validate_email("user@example.com")) # True
print(validate_email("invalid-email")) # False
2. Explain a piece of code
Task: Understand a complex list comprehension.
Prompt:
Explain the following code line by line, as if to a junior developer:
result = [x * 2 for x in range(10) if x % 2 == 0]
Example result:
- range(10) generates numbers from 0 to 9.
- if x % 2 == 0 filters only even numbers.
- x * 2 doubles each even number.
- The result is a new list: [0, 4, 8, 12, 16].
3. Write unit tests for an existing function
Task: Create tests for a calculate_discount function.
Prompt:
Given the function below, write three unit tests using Python's unittest framework: one for a normal discount, one for a zero discount, and one for a negative price edge case.
def calculate_discount(price, discount_percent):
return price * (1 - discount_percent / 100)
Example result:
import unittest
class TestCalculateDiscount(unittest.TestCase):
def test_normal_discount(self):
self.assertEqual(calculate_discount(100, 20), 80.0)
def test_zero_discount(self):
self.assertEqual(calculate_discount(50, 0), 50.0)
def test_negative_price(self):
with self.assertRaises(ValueError):
calculate_discount(-10, 10)
if __name__ == '__main__':
unittest.main()
Advanced Prompts
4. Debug a runtime error
Task: Fix a 'list index out of range' error in a function that finds the second largest number.
Prompt:
The following code raises an IndexError. Identify the bug and fix it. Explain why the error occurs and how your fix resolves it.
def second_largest(nums):
sorted_nums = sorted(nums)
return sorted_nums[-2]
Example result:
Bug: If nums has fewer than 2 elements, sorted_nums[-2] raises an IndexError.
Fix: Add a check for list length.
def second_largest(nums):
if len(nums) < 2:
return None
sorted_nums = sorted(nums)
return sorted_nums[-2]
5. Refactor a monolithic function into smaller ones
Task: Split a long function that processes user data.
Prompt:
Refactor the following function into three smaller functions: `validate_user`, `format_name`, and `process_user`. Each should have a single responsibility. Use descriptive names and add type hints.
def handle_user(user):
if not user.get('name') or not user.get('email'):
return 'Invalid'
name = user['name'].strip().title()
return f"{name} <{user['email']}>"
Example result:
def validate_user(user: dict) -> bool:
return bool(user.get('name') and user.get('email'))
def format_name(name: str) -> str:
return name.strip().title()
def process_user(user: dict) -> str:
if not validate_user(user):
return 'Invalid'
return f"{format_name(user['name'])} <{user['email']}>"
6. Optimize a slow SQL query
Task: Improve a query that takes too long on large datasets.
Prompt:
The following SQL query runs slowly on a table with 10 million rows. Analyze it and suggest optimizations (indexes, query restructuring). Provide the optimized query.
SELECT * FROM orders WHERE customer_id IN (SELECT id FROM customers WHERE signup_date > '2025-01-01');
Example result:
Issue: The subquery is evaluated for each row in orders. No index on signup_date or customer_id.
Optimizations:
1. Add index: CREATE INDEX idx_customer_signup ON customers(signup_date);
2. Use a JOIN instead of subquery:
SELECT o.* FROM orders o
JOIN customers c ON o.customer_id = c.id
WHERE c.signup_date > '2025-01-01';
7. Convert code between programming languages
Task: Translate a JavaScript function to Python.
Prompt:
Convert the following JavaScript function to idiomatic Python. Use list comprehensions and proper error handling.
function sumPositive(arr) {
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > 0) {
sum += arr[i];
}
}
return sum;
}
Example result:
def sum_positive(arr):
return sum(x for x in arr if x > 0)
8. Generate a Dockerfile for a Python app
Task: Create a production-ready Dockerfile.
Prompt:
Write a Dockerfile for a Python Flask application that:
- Uses Python 3.12 slim image
- Installs dependencies from requirements.txt
- Exposes port 5000
- Runs with a non-root user for security
- Minimizes image size
Example result:
FROM python:3.12-slim
RUN useradd -m appuser
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
USER appuser
EXPOSE 5000
CMD ["python", "app.py"]
9. Explain a design pattern with a real-world analogy
Task: Understand the Observer pattern.
Prompt:
Explain the Observer design pattern using a real-world analogy (like a newsletter subscription). Then provide a simple Python implementation with two subscribers.
Example result:
Analogy: A newsletter publisher (subject) sends emails to all subscribers (observers). When a new issue is released, each subscriber gets notified automatically.
Implementation:
class Publisher:
def __init__(self):
self._subscribers = []
def subscribe(self, observer):
self._subscribers.append(observer)
def notify(self, message):
for obs in self._subscribers:
obs.update(message)
class Subscriber:
def update(self, message):
print(f"Received: {message}")
Expert Prompts
10. Design a microservices architecture
Task: Outline a system for an e-commerce platform.
Prompt:
Design a microservices architecture for an e-commerce platform. Identify 5 core services (e.g., inventory, payment). For each service, describe its responsibility, API endpoints (RESTful), and how they communicate (sync vs async). Include a diagram description in text.
Example result:
Services:
1. User Service — manages profiles, authentication (REST).
2. Product Catalog — CRUD for products, search (REST).
3. Order Service — handles orders, uses async messaging for payment.
4. Payment Service — processes payments via Stripe API (async via RabbitMQ).
5. Inventory Service — tracks stock levels, emits events on low stock.
Communication: Use REST for synchronous queries, RabbitMQ for events (e.g., order placed triggers payment).
11. Generate a comprehensive API specification
Task: Create an OpenAPI spec for a simple task manager.
Prompt:
Write an OpenAPI 3.0 specification for a task manager API with endpoints: create task (POST /tasks), list tasks (GET /tasks), and delete task (DELETE /tasks/{id}). Include request/response schemas.
Example result:
openapi: 3.0.0
info:
title: Task Manager API
version: 1.0.0
paths:
/tasks:
post:
summary: Create a new task
requestBody:
required: true
content:
application/json:
schema:
type: object
properties:
title:
type: string
responses:
'201':
description: Task created
12. Refactor a legacy codebase with strategy pattern
Task: Replace conditional logic with the Strategy pattern.
Prompt:
The following code violates the Open/Closed principle. Refactor it using the Strategy pattern. Provide the interface, concrete strategies, and context class.
def calculate_shipping(order, method):
if method == 'standard':
return order.weight * 0.5
elif method == 'express':
return order.weight * 1.5
else:
return 0
Example result:
from abc import ABC, abstractmethod
class ShippingStrategy(ABC):
@abstractmethod
def calculate(self, order):
pass
class StandardShipping(ShippingStrategy):
def calculate(self, order):
return order.weight * 0.5
class ExpressShipping(ShippingStrategy):
def calculate(self, order):
return order.weight * 1.5
class ShippingCalculator:
def __init__(self, strategy: ShippingStrategy):
self._strategy = strategy
def calculate(self, order):
return self._strategy.calculate(order)
13. Write a CI/CD pipeline configuration
Task: Generate a GitHub Actions workflow for a Node.js app.
Prompt:
Create a GitHub Actions workflow that:
- Triggers on push to main and pull requests
- Runs npm install and npm test
- Builds the project
- Deploys to AWS Elastic Beanstalk on successful main push
Example result:
name: CI/CD Pipeline
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- run: npm install
- run: npm test
- run: npm run build
- name: Deploy to EB
if: github.ref == 'refs/heads/main'
run: echo "Deploy step would go here"
14. Generate a secure authentication middleware
Task: Create a JWT-based auth middleware for Express.js.
Prompt:
Write an Express.js middleware that:
- Extracts a JWT from the Authorization header (Bearer scheme)
- Verifies the token using a secret
- Attaches decoded user info to req.user
- Returns 401 if token is missing or invalid
Example result:
const jwt = require('jsonwebtoken');
function authMiddleware(req, res, next) {
const authHeader = req.headers.authorization;
if (!authHeader || !authHeader.startsWith('Bearer ')) {
return res.status(401).json({ error: 'Missing token' });
}
const token = authHeader.split(' ')[1];
try {
const decoded = jwt.verify(token, process.env.JWT_SECRET);
req.user = decoded;
next();
} catch (err) {
return res.status(401).json({ error: 'Invalid token' });
}
}
15. Review a pull request for security issues
Task: Identify vulnerabilities in a code snippet.
Prompt:
Review the following code for security flaws. Focus on SQL injection, XSS, and hardcoded secrets. Suggest fixes.
app.get('/user', (req, res) => {
const id = req.query.id;
const query = `SELECT * FROM users WHERE id = ${id}`;
db.execute(query);
});
Example result:
Flaws:
1. SQL injection: id is interpolated directly.
2. No input validation.
Fix: Use parameterized queries.
app.get('/user', (req, res) => {
const id = parseInt(req.query.id, 10);
if (isNaN(id)) return res.status(400).send('Invalid ID');
db.execute('SELECT * FROM users WHERE id = ?', [id]);
});
16. Explain a distributed system concept with a diagram
Task: Describe the CAP theorem.
Prompt:
Explain the CAP theorem with a text-based diagram. Give an example of a CP system and an AP system, and explain the trade-offs.
Example result:
CAP Theorem: A distributed system can only guarantee two of three: Consistency, Availability, Partition Tolerance.
CP (e.g., MongoDB with single master)
/ \
/ \
Consistency Availability
\ /
\ /
AP (e.g., Cassandra)
Trade-off: CP systems sacrifice availability during network partitions; AP systems sacrifice immediate consistency.
17. Generate a complete error-handling strategy
Task: Design a global error handler for a Python web app.
Prompt:
Create a global error handler for a FastAPI application that:
- Catches all unhandled exceptions
- Returns a JSON response with status code, error message, and request ID
- Logs the error with traceback
- Distinguishes between HTTPException and generic errors
Example result:
from fastapi import Request, HTTPException
from fastapi.responses import JSONResponse
import logging
import uuid
logger = logging.getLogger(__name__)
async def global_error_handler(request: Request, exc: Exception):
request_id = str(uuid.uuid4())
if isinstance(exc, HTTPException):
status_code = exc.status_code
detail = exc.detail
else:
status_code = 500
detail = "Internal server error"
logger.error(f"Unhandled exception: {exc}", exc_info=True)
return JSONResponse(
status_code=status_code,
content={"request_id": request_id, "error": detail}
)
18. Propose a database migration strategy
Task: Plan zero-downtime migration from MySQL to PostgreSQL.
Prompt:
Outline a strategy for migrating a production database from MySQL to PostgreSQL with zero downtime. Include steps for schema conversion, data sync, and cutover. Mention tools like pgloader or AWS DMS.
Example result:
Strategy:
1. Schema conversion: Use pgloader to convert MySQL schema to PostgreSQL.
2. Full load: Copy all data to the new PostgreSQL instance.
3. Continuous sync: Set up change data capture (CDC) using Debezium or AWS DMS to replicate ongoing changes.
4. Cutover: Switch application to read from PostgreSQL, then write both databases temporarily.
5. Validation: Compare row counts and checksums.
6. Cleanup: Remove MySQL instance after a monitoring period.
Conclusion
These 18 prompts cover the full spectrum of software development with GPT-4, from writing simple functions to designing distributed architectures. The key to getting the most out of these prompts is specificity: always provide context, constraints, and examples. As you integrate these prompts into your daily workflow, you'll find that GPT-4 becomes a reliable pair programmer, a thorough code reviewer, and a thoughtful architect. Start with the basic prompts today, and gradually adopt the advanced and expert ones as your confidence grows. Happy coding!
Comments