We've all experienced those moments when we feel stuck or overwhelmed with repetitive tasks or a challenging programming problem. Fortunately, AI-powered tools are mainstream nowadays, and unlike popular belief, it is not like AI will take our jobs... So easily. We can use these tools to gather inspiration and even find completely usable solutions.

Among developers, two of the most popular AI tools are ChatGPT and GitHub Copilot. Both are generative AI tools and have their use cases, but we're focusing on ChatGPT this time because it's more accessible —in terms of pricing— and can boost your productivity. I want to show you a set of curated prompts that will unlock the full potential of the technology you're using.

Table of Contents

Scenario 1: When you need assessment
Code Review
Code Refactor
Code Optimization
Suggestions
Examples
Scenario 2: When you need to review
Bug detection and fixing
Testing
Examples
Scenario 3: When you need to understand better
Code Explanation
Example
Scenario 4: When you need a little push
Code Generation
Code Completion
Code Conversion
Examples
Scenario 5: When you need an assistant
Mock data generation
Documentation
Examples

Scenario 1: When you need assessment

Code Review

Code review is a very important practice during the software development cycle, and it can often be difficult to catch every potential issue when you're working alone. With the help of ChatGPT, you can identify deficiencies and security vulnerabilities in your code to make it more efficient and secure.

  • Prompt 1: Can you provide feedback on my [programming language/technology/framework] code and suggest some improvements
  • Prompt 2: Identify any security vulnerabilities in the following code: [code snippet]

Code Refactor

Imagine yourself coding, in the zone, finishing a feature when you realize some older code could use a little 'touch-up.' In case you didn't know, this is called refactoring, and ChatGPT can help you with that if you give enough context.

  • Prompt 1: Refactor the given [language] code to improve performance: [code block]
  • Prompt 2: Refactor the below component code to be responsive across mobile, tablet, and desktop screens: [code block]
  • Prompt 3: Suggest descriptive and meaningful names for variables and functions, making it easier to understand the purpose of each element in your code: [code snippet]

Code Optimization

It's easy to neglect performance while building a feature because we focus on making it work first. Besides, premature optimization can be counterproductive.

However, performance is always critical, and ChatGPT can help us find optimization opportunities by asking nicely.

  • Prompt: Optimize the following [programming language] code which [explain the functioning]: [code snippet]
  • Prompt: Rewrite [programming language] code to improve [performance/scalability/reliability] : [code snippet]
  • Prompt: How can I optimize [functionality] in [programming language] code?
  • Prompt: Suggest ways to improve the performance of [specific feature] in [programming language] code.
  • Prompt: Can you recommend any optimization techniques for [programming language] code?
  • Prompt: I want you to act as a code optimizer and suggest improvements for the following code to optimize its performance: [code snippet].

Suggestions

ChatGPT can be your go-to guru for tech choices, ranging from picking the right framework or library for your project to designing systems using specific technology stacks, whether you're crafting a web app, a mobile application, or a distributed system.

  • Prompt: Can you recommend a suitable front-end framework/library for my website? I’m making [type of website].
  • Prompt: Contrast the design and architecture with [comma-separated list of technologies] as the technology stack.
  • Prompt: You are an expert at system design and architecture. Tell me how to design a [system]. The technology stack is [comma-separated list of technologies].
  • Prompt: Suggest possible solutions to [problem with code].
  • Prompt: Provide suggestions to fix [specific issue] in [programming language] code.
Examples:
  • Code review: Can you provide feedback on my TypeScript code and suggest some improvements?
const fetch = (page, limit) => {
  return fetch(runtimeConfig.apiBaseUrl + '/jobs?page=' + page + '&limit=' + limit)
}
  • Code review: Identify any security vulnerabilities in the following code:
const fetchJobs = () => {
  fetch('https://api.jobdaily.com/jobs?api-key=927dd516-5609-48f7-b004-d7f4bb29c9d5');
}
  • Code refactor: Suggest descriptive and meaningful names for variables and functions, making it easier to understand the purpose of each element in your code:
const url = '<https://api.elaniin.dev>'
const m = '/jobs'

const r = await fetch(url + m);
const j = await r.json();
const job = r.data[0]
  • Code optimization: I want you to act as a code optimizer and suggest improvements for the following code to optimize its performance:
SELECT COUNT(*) AS total_orders
FROM orders
WHERE customer_id IN (
    SELECT customer_id
    FROM customers
    WHERE customer_name = 'your_desired_customer_name'
);
  • Suggestions: Provide suggestions to fix N+1 in this PHP code:
$usersWithPosts = User::query()
  ->get()
  ->map(function (User $user) {
    return collect($user->toArray())
      ->put(
        'posts',
        Post::query()->where('user_id', $user->id)
      );
  });

Scenario 2: When you need to review

Bug detection and fixing

Every developer knows the experience of pouring countless hours into debugging a piece of code. It can be a frustrating process that stands in the way of our productivity and ultimately pushes back delivery timelines. Using these prompts can quickly help you identify the bug disturbing your code and help you fix it.

  • Prompt: Find any bugs in the following code: [code snippet]
  • Prompt: How do I fix the following [programming language] code which [explain the functioning]? [code snippet]
  • Prompt: Provide guidance on how to resolve [issue with code].
  • Prompt: Can you explain the cause of [specific error] in [programming language] code?
  • Prompt: I want you to act as a debugging assistant and provide me with possible reasons why [error message or behavior] is occurring.
  • Prompt: I am getting the error [error] from the following snippet of code: [code snippet]. How can I fix it?

Testing

ChatGPT can assist you to verify your code against the required standards. Here are some handy prompts to guide you in crafting unit tests and generating test case lists.

  • Prompt: Write unit tests for the following [library/ framework] component [component code] using [testing framework/ library]
  • Prompt: Generate a list of test cases to manually test user registration in a web/ mobile application.
Examples:
  • Bug detection and fixing: I am getting an infinite loop when running the code below. How can I fix it?
useEffect(() => {
  setUser(UserService.find(props.userId));
});
  • Testing: Generate a list of test cases for the following Rock Paper Scissors Spock Lizard function:
/**
 * RPSSL Algorithm
 *
 * 0: Rock
 * 1: Paper
 * 2: Scissors
 * 3: Spock
 * 4: Lizard
 */
export function winner (playerOne: number, playerTwo: number): number {
  if (playerOne === playerTwo) {
    return 0 // Tie.
  }

  const n = 5
  const difference = (n + playerOne - playerTwo) % n

  if (difference % 2 === 1) {
    return 1 // Player 1.
  } else if (difference % 2 === 0) {
    return 2 // Player 2.
  }

  return 0
}

Scenario 3: When you need to understand better

Code Explanation

Ever found yourself scratching your head, staring at a cryptic piece of code as if it's some ancient hieroglyph? Well, use ChatGPT as a translator.

This feature is quite useful when you are trying to comprehend a piece of code written by others.

  • Prompt: What does this code do: [accepted answer code from stack overflow]
  • Prompt: Explain how the [concept or function] works in [programming language].
  • Prompt: Explain the following [language] snippet of code: [code block]
Example:
  • Code explanation: Explain the following Java snippet:
import java.time.LocalDateTime;
import java.time.ZoneOffset;

public class UtcTimePrinter {
    public static void main(String[] args) {
        LocalDateTime utcTime = LocalDateTime.now(ZoneOffset.UTC);
        System.out.println("Current UTC time: " + utcTime);
    }
}

Scenario 4: When you need a little push

Code Generation

This is perhaps the type of prompt I use the most when I have a creative block. ChatGPT, aside from human-like text, can also generate useful code snippets when prompted correctly.

  • Prompt: Can you create code for [specific feature] in [programming language]?
  • Prompt: Generate a semantic and accessible HTML and (framework) CSS [UI component] consisting of [component parts]. The [component parts] should be [layout].
  • Prompt: The database has [comma-separated table names]. Write a [database] query to fetch [requirement].
  • Prompt: Write a/ an [framework] API for [functionality]. It should make use of [database].
  • Prompt: Write a program/function to [explain functionality] in [programming language]
  • Prompt: I want you to act as a code generator and create a [language] code for [task] using [framework or library]
  • Prompt: Craft a code snippet in [programming language] for [task or feature].

Code Completion

It's like having a co-developer who understands your coding style and context, offering insightful code completion suggestions. It’s like a Copilot 😉

  • Prompt: Generate code completions for [programming language] code based on [context of code].
  • Prompt: List possible code completions for [programming language] code that [context of code].
  • Prompt: How can I complete [partial code] in [programming language]
  • Prompt: I want you to act as a code completion tool and suggest code completion for [incomplete code snippet]
  • Prompt: Complete the code below:[code snippet]

Code Conversion

Researching solutions is a common task for developers, and sometimes, the solutions available are in a different language or technology than the one we're using. Sometimes we can do it without any help since it's just syntax, but sometimes is a bit more complex, and that is when ChatGPT comes in handy with code translation prompts.

  • Prompt: Convert the below code using [CSS framework] to use [CSS framework]: [code snippet]
  • Prompt: Convert the below code snippet from [language/ framework] to [language/ framework]: [code snippet]
Examples:
  • Code generation: Craft a code snippet in Go for credit card validation using Luhn’s algorithm
  • Code completion: Complete the code below:
/**
 * Remove any characters that could lead to an XSS-attack
 */
const sanitizeString = (string: string) => {
  
}
  • Code conversion: Convert the below code snippet from PHP to Go:
class Client
{
    public function request(string $url, string $method = 'GET', array $headers = [], array $params = [])
    {
        $curl = curl_init();

        curl_setopt($curl, CURLOPT_URL, $url);

        $method = strtoupper($method);

        if ($method === 'POST') {
            curl_setopt($curl, CURLOPT_POST, true);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
        } elseif ($method !== 'GET') {
            curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);

            if (!empty($params)) {
                curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($params));
            }
        }

        if (!empty($headers)) {
            curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        }

        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, true);

        $response = curl_exec($curl);

        if (curl_errno($curl)) {
            throw new Exception(curl_error($curl));
        }

        curl_close($curl);

        return $response;
    }
}

Scenario 5: When you need an assistant

Mock data generation

ChatGPT it's like your trusty assistant. It swiftly creates realistic and representative data, be it for testing or demonstration, ready to generate mock data for various domains and formats.

  • Prompt: You can also enter prompts after every response for more fine-grained control:
    - Give me a list of [number] fields for [entity] on an e-commerce site.
    - Add an “id” field that will be unique to each [entity]. Replace [existing field] with [new field].
    - Generate a sample [data format] of [number] such [entity] with realistic values.
  • Prompt: Generate a sample [data format] of [number] [entity] for a [domain].

Documentation

Embarking on a new project can be an exciting and challenging journey. Whether you're working solo on a new project or a team player, there's one constant that remains vital - solid documentation.

  • Prompt: Describe the process of generating documentation from [programming language] codebase.
  • Prompt: Guide writing effective documentation for [software solution].
  • Prompt: What tools are available for automatically generating documentation from [programming language] codebase?
  • Prompt: Provide instructions for generating user manuals from [programming language] code.
  • Prompt: I want you to act as a documentation generator and create a [type of documentation] document for [code or project]
  • Prompt: Generate API documentation for [programming language] codebase.
Examples:
  • Mock data generation: Generate a sample JSON of 5 IP addresses for geolocation.
  • Documentation: Generate OpenAPI documentation for the API endpoint /companies which returns an array of companies with their ID as a UUIDv4 string, name as string, code as an integer, and registration date time as DateTime.

Emerging as the trusty sidekick for developers, ChatGPT prompts are streamlining the process of creating, maintaining, and enhancing code and documentation. From acting as a documentation generator to guiding the process and providing insights about the various tools available, it undoubtedly offers a helping hand.

A final tip when using LLMs: Give the AI as much context as you can using interfaces, strict type definitions, etc. It will make your life easier.

References & Resources