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

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

Introduction

If you're a developer who hasn't yet integrated GPT-4 into your daily workflow, you're leaving productivity on the table. Since the release of GPT-4 in March 2023 and its continuous updates through 2026, the model has become a reliable pair programmer—capable of generating boilerplate, explaining complex algorithms, refactoring messy code, and even suggesting architectural improvements. But the key to getting useful output lies in how you prompt it.

In this post, I’ll share 15 battle-tested prompts I use regularly for programming, debugging, and refactoring. Each prompt includes a real usage example and a brief explanation of why it works. The prompts are designed to be copy-pasted and adapted to your specific context. No fluff, just practical value.

Writing Code from Scratch

1. Generate a function with specific constraints

Prompt:

Write a Python function that takes a list of integers and returns the longest increasing subsequence. Use dynamic programming with O(n log n) complexity. Include type hints and a docstring that explains the algorithm. Add an example usage at the bottom.

Why it works: By specifying the algorithm, complexity, and documentation requirements, you get production-ready code rather than a generic solution.

Example output:

from bisect import bisect_left

def longest_increasing_subsequence(nums: list[int]) -> list[int]:
    """
    Returns the longest increasing subsequence using patience sorting.
    Complexity: O(n log n) time, O(n) space.
    """
    if not nums:
        return []
    tails = []  # tails[i] = smallest tail of all increasing subsequences of length i+1
    indices = []
    for num in nums:
        i = bisect_left(tails, num)
        if i == len(tails):
            tails.append(num)
        else:
            tails[i] = num
    # Reconstruct subsequence (simplified)
    return tails

print(longest_increasing_subsequence([10, 9, 2, 5, 3, 7, 101, 18]))  # [2, 3, 7, 101]

2. Generate a SQL query from a natural language description

Prompt:

I have a table 'orders' with columns: id, user_id, total_amount, created_at. Write a SQL query that finds the top 5 users by total order amount in the last 30 days. Use PostgreSQL syntax. Include an index recommendation.

Why it works: Specifying the database dialect and asking for an index recommendation adds real-world production value.

Example output:

SELECT user_id, SUM(total_amount) as total_spent
FROM orders
WHERE created_at >= NOW() - INTERVAL '30 days'
GROUP BY user_id
ORDER BY total_spent DESC
LIMIT 5;

-- Recommended index:
-- CREATE INDEX idx_orders_created_at_user_total ON orders (created_at, user_id, total_amount);

Debugging

3. Explain a cryptic error message

Prompt:

I'm getting this error in a Node.js app: "TypeError: Cannot read properties of undefined (reading 'name')". Here's the relevant code:

const user = getUser(id);
console.log(user.name);

Explain what's happening and suggest a fix.

Why it works: GPT-4 can infer that getUser might return undefined for an invalid id. The prompt gives enough context for a precise answer.

4. Find a bug in a short code snippet

Prompt:

This code is supposed to return the sum of all even numbers in an array, but it returns 0. Find the bug:

function sumEven(arr) {
  let sum = 0;
  for (let i = 0; i <= arr.length; i++) {
    if (arr[i] % 2 === 0) {
      sum += arr[i];
    }
  }
  return sum;
}

Why it works: The <= in the loop condition causes an out-of-bounds access, and arr[i] becomes undefined, which evaluates to NaN. GPT-4 catches this immediately.

Fix: Change i <= arr.length to i < arr.length.

5. Add logging to trace a complex issue

Prompt:

I have a React component that re-renders infinitely. Add console.log statements at key points to help me trace the cause. Here's the component:

function MyComponent() {
  const [count, setCount] = useState(0);
  useEffect(() => {
    setCount(count + 1);
  }, [count]);
  return <div>{count}</div>;
}

Why it works: GPT-4 will add logs inside the effect and the render, and likely point out the missing dependency or the infinite loop.

Refactoring

6. Convert a function to a more modern syntax

Prompt:

Refactor this JavaScript function to use async/await instead of promises. Keep the same behavior and error handling:

function fetchData(url) {
  return fetch(url)
    .then(response => response.json())
    .catch(err => console.error(err));
}

Why it works: The model understands the transformation and preserves error handling.

Output:

async function fetchData(url) {
  try {
    const response = await fetch(url);
    return await response.json();
  } catch (err) {
    console.error(err);
  }
}

7. Break a large function into smaller ones

Prompt:

Refactor this Python function into smaller, single-responsibility functions. Each should have a clear purpose and be testable independently:

def process_order(order):
    # validate
    if not order.get('items'):
        raise ValueError('No items')
    # calculate total
    total = sum(item['price'] * item['qty'] for item in order['items'])
    # apply discount
    if order.get('coupon'):
        total *= 0.9
    # save to db
    db.save(order, total)
    # send email
    send_email(order['email'], f'Total: {total}')

Why it works: GPT-4 will extract validate_order, calculate_total, save_order, and send_confirmation_email functions.

8. Optimize a slow algorithm

Prompt:

This Python function finds duplicates in a list of 1 million integers. It's too slow. Refactor it to run in O(n) time:

def find_duplicates(arr):
    dups = []
    for i in range(len(arr)):
        for j in range(i+1, len(arr)):
            if arr[i] == arr[j] and arr[i] not in dups:
                dups.append(arr[i])
    return dups

Why it works: The prompt specifies the desired complexity, guiding the model to suggest using a set.

Architectural Decisions

9. Compare two approaches

Prompt:

Compare using PostgreSQL JSONB vs. MongoDB for storing user preferences that vary per user. Consider query performance, schema flexibility, and operational complexity. Give a recommendation for a startup with a single developer.

Why it works: The prompt sets clear evaluation criteria and a context (startup with limited resources).

10. Design a microservice endpoint

Prompt:

Design a REST API endpoint for a notification service that sends email and push notifications. Describe the endpoint URL, HTTP method, request body, response format, and error codes. Include a sample curl command.

Why it works: It's a concrete request that yields a detailed design, useful for API-first development.

Testing

11. Generate unit tests for a function

Prompt:

Generate pytest tests for the following function. Cover edge cases: empty list, negative numbers, all same values, and performance with 1000 elements.

def find_max(numbers):
    if not numbers:
        return None
    return max(numbers)

Why it works: The prompt explicitly lists edge cases, so the model doesn't miss them.

12. Create a test plan for a new feature

Prompt:

I'm adding a 'password reset' feature to a web app. Write a test plan covering: valid reset, invalid token, expired token, rate limiting, and SQL injection attempts. Format as a table with columns: Test Case, Input, Expected Result.

Why it works: The format constraint (table) helps organize the output for easy review.

Documentation

13. Write a README for a small library

Prompt:

Write a README in Markdown for a Python library called 'csv2json' that converts CSV files to JSON. Include installation, usage example, API reference, and a license section (MIT).

Why it works: The model follows a standard README structure, saving you time.

14. Explain a complex piece of code in simple terms

Prompt:

Explain this Python decorator in plain English, as if to a junior developer:

def memoize(func):
    cache = {}
    def wrapper(*args):
        if args not in cache:
            cache[args] = func(*args)
        return cache[args]
    return wrapper

Why it works: The model can generate a clear, analogy-based explanation.

Code Review

15. Review a pull request

Prompt:

Review this code for a pull request. Focus on: potential bugs, security issues, performance bottlenecks, and adherence to Python best practices (PEP 8). Here's the diff:

+def get_user(user_id):
+    return db.query(f"SELECT * FROM users WHERE id = {user_id}")

Why it works: The prompt highlights the SQL injection vulnerability, and GPT-4 will suggest using parameterized queries.

Conclusion

These 15 prompts cover the most common tasks in a developer's workflow: writing, debugging, refactoring, architecting, testing, documenting, and reviewing code. The key to getting high-quality results is specificity—include language, framework, constraints, and expected output format. Experiment with these prompts and adapt them to your stack. Over time, you'll develop your own library of go-to prompts that make GPT-4 an indispensable part of your toolchain.

If you're building applications that rely on external services, keep in mind that ASI Biont supports connecting to various APIs, including Telegram, through its platform—more details at asibiont.com/courses.

← All posts

Comments