Back to Blog

how to get a job as a web developer 2024
Data Science

Mastering Coding Prompts: Leveraging AI for Optimal Outcomes

11 minute read | October 13, 2023
Kindra Cooper

Written by:
Kindra Cooper

Ready to launch your career?

Generative AI is already a must-have programming tool for most developers. A recent GitHub survey found that 92% of programmers already use AI tools. Seventy percent of respondents reported seeing benefits, such as improved code quality, faster output, and fewer production-level incidents.

Despite the initial brouhaha over the possibility of companies replacing full-time human programmers with generative AI, these tools have severe limitations—namely, no business acumen or real-world context–and are best entrusted with boilerplate code.

“When companies write software, the code is proprietary, so the most you can do with AI is use it to generate bits and pieces of code,” says Jasmeet Singh, a senior software engineer at HashiCorp and a mentor for Springboard’s Software Engineering Bootcamp. “You can’t ask ChatGPT to create a new version of Facebook for you. You might get the code for the login button or some other function, but you won’t get a whole website.”

Understanding Coding Prompts

Developers are using AI-powered coding assistants to up their productivity and devise workarounds for coding problems. These tools can be used within an Integrated Development Environment (IDE) to analyze code, provide intelligent suggestions, flag errors, and generate boilerplate code snippets.

Meanwhile, ChatGPT has diverted traffic from Stack Overflow as developers turn to the bot to answer their questions. For example, they might ask the bot to explain a concept in data structures and algorithms they hadn’t considered since their last job interview.

“Developers can use AI to do straightforward tasks like create post-API or guest request API,” says Peter Nsaka, a senior software engineer at Shopify and a mentor for Springboard’s Software Engineering Bootcamp. “But AI doesn’t understand the nuances of business logic, which is where the human developer’s knowledge is invaluable.”

That said, here’s what AI can do for you:

  • Code completion – Coding copilots prompt you with autocomplete suggestions as you write code. Alternatively, copy-paste code snippets into ChatGPT and ask the bot to complete it. 
  • Error detection – The AI automatically alerts you to syntax and logic errors.
  • Code refactoring – Copilots can suggest code structure, organization, and readability improvements when working on a particular function or class. 

Programming Prompt Examples

Prompting is critical whether you’re using ChatGPT or an AI coding copilot. Skilled developers dedicate time to thinking through the project before writing a single line of code. Similarly, you should provide the AI with the context of what you want to accomplish before jumping in.

When “communicating” with AI, pretend you’re doing pair programming with another developer. Github Copilot leverages context from the code and comments you write to suggest code. You can convert comments to code, autofill repetitive code, and show alternative suggestions. 

The difference between using a coding copilot and a generative AI tool like ChatGPT is that an AI copilot auto-generates prompts based on the context provided by code snippets and comments you’ve already written, hence its ability to make real-time suggestions as you write code. 

Think of ways to break down the problem into smaller pieces so the AI can best assist you.

Some everyday use cases for AI code generation are:

Unit Tests 

Design a prompt to request a unit test for a function.

“Create a unit test function called `test_factorial_function` to test the `factorial` function. The `factorial` function takes an integer `n` as input and calculates the factorial of `n`.

Write test cases within the `test_factorial_function` to cover the following scenarios:

1. Test that the factorial of 0 is 1.

2. Test that the factorial of 1 is 1.

3. Test that the factorial of 5 is 120.

4. Test that calling the `factorial` function with a negative integer raises a ValueError.

If any of the test cases fail, include an appropriate error message indicating the expected and actual outcomes.

Finally, run the `test_factorial_function` and print “All tests passed!” if all assertions are successful.”

Write a Function 

Pass a problem to the model to get a function that solves the problem. 

  • Provide a concise description of the problem that needs solving. State the input, the desired output, and applicable constraints or requirements. Define the function name, its parameters, and their types. This ensures the generated code aligns with the expected function structure. 
  • Include examples of input-output pairs to illustrate how the function should behave. These serve as a reference for generating the correct logic.

Write a function to calculate the area of a circle given its radius. The function should include a check to ensure the radius is non-negative. If a negative radius is provided, the function raises a ‘ValueError’ to indicate invalid input.

Input-Output Pairs:

  • Input: radius = 5, Output: 78.53975
  • Input: radius = 0, Output: 0.0
  • Input: radius = -10, Output: ValueError
  • Input: radius = 2.5, Output: 19.6349375.” 

Create a Class

Use a prompt to describe the purpose of a class and generate code that defines the class returned.

“Generate the code to define a Python class named Car. This class should encapsulate the concept of a car and have the attributes ‘make,’ ‘model,’ ‘year’ and ‘mileage.’ Include a description with details about the purpose of the class, the attributes, their data types, and the methods defined for this class. Ensure the code is well-commented to explain each part of the class definition.”

Define Features 

Use bullet points to list the key features you want to implement. Include details about how you envision the user interface, interactions, and any specific behavior you expect. If you’re using an AI copilot, you would enter this information as a comment. 

EXAMPLE PROMPT

Description: In our to-do list application, we want to allow users to set due dates for their tasks. This will help users prioritize their tasks and stay organized. A due date should be associated with each task, and the user should be able to view, edit, and sort tasks based on their due dates. Additionally, overdue tasks should be highlighted to catch the user’s attention.

Requirements:

  • Each task should have an associated due date, which includes the date and time.
  • Users should be able to set the due date when creating or editing a task.
  • The task list should be sortable based on due dates.
  • Overdue tasks should be visually highlighted in the task list.
  • Users should receive a notification or reminder when a task’s due date is reached.
  • Due dates should be displayed in a user-friendly format, such as “Today”, “Tomorrow”, or the actual date if it’s further in the future.

Still, no matter how detailed your prompt, Shahid cautions against relying too much on the AI’s output.

“It definitely helps to add a lot of detail to your prompt, but the output still might not be relevant, accurate, or production-ready,” he says. “Humans are the ones who can translate business requirements into software requirements, while AI cannot.”

How To Structure a Programming Prompt

  1. State the role you want ChatGPT to assume (e.g., “You’re a junior developer at a  mobile app development company.”) By giving the AI a role, you prompt it to tap into the most relevant knowledge from its training data. 
  2. Specify your chosen programming language. “Your programming language is Python.”
  3. Describe the project and its purpose. “I’m building a mobile app to help mid-career professionals manage their fitness routines. The app aims to help users stick to a weekly workout schedule. We can reward them for adherence using gamification elements to keep them motivated.” 
  4. State the desired functionalities of the application using bullet points. 
  • “Users must be able to log workout activity in the app.”
  • “Weekly workout activity will be logged in a dashboard and summarized in a weekly email.”
  • “Pop-up notification reminders 2 hours ahead of scheduled workout time.” 
  1. Explain the desired format for your output. “Generate the code block and explain.” 

Extra Tips for Using GitHub Copilot

If you want Github Copilot to retrieve data from an API, tell it what type of data you want to retrieve, how to process it, and what API endpoint you want to hit. 

Keep tabs with relevant files open to provide additional context to the AI. GitHub Copilot boasts a  ‘neighboring tabs’ feature that allows the AI to contextualize your code by processing all the files open in your IDE instead of just the single file you’re working on. 

Writing Prompts for Debugging and Error Handling

ChatGPT can find errors in your code if you share the code snippet and error message. Please note that the examples below are highly simplified for the sake of showing each concept in action. 

  • Identify the problem. 

Ask ChatGPT to interpret the error message or explain the unexpected behavior. “You can also ask it to isolate the problem by identifying the exact line or lines of code causing the error. 

“My code shows the following error message TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’. Can you explain the root cause of this error message? Next, identify which lines of code are causing the error [copy-paste code snippet here].

age = 25

name = “Alice”

result = age + ” years old ” + name

print(result)

coding prompts,  explanation of error
  • Ask it to tweak the code because you’re not getting the results you’re looking for (i.e. logical error). 

“When I try to access an element at an index in a list, the index goes out of bounds, resulting in an ‘IndexError.’ Can you describe possible reasons for this unexplained behavior and troubleshoot it?”

coding prompts, IndexError
  • Ask ChatGPT to explain the code fix so you can reproduce it throughout your code. Ask it to explain the code’s purpose, structure, and syntax. 

Can you explain the code fix, including its purpose, structure, and syntax? Walk me through how this code snippet effectively prevents the ‘IndexError’ and allows safe access to elements in the list. Tell me how to reproduce this pattern in other parts of the code where index-related issues might arise.”

coding prompts, my_list

How To Structure a Debugging Prompt

  1. Explain the problem. However, don’t give it the whole error stack, as this may confuse the AI.

“I’m getting the following error message [insert error message]. Tell me how to fix it.”

  1. Assign a role. Ask ChatGPT to be a senior developer or expert engineer for more advanced advice. “You’re a React expert. Help me solve this error.”
  2. Mention the framework and operating system (e.g. Windows, Linux).
  3. Specify the programming language and libraries you’re using.
  4. Paste the applicable code snippet. For example, if you have an error related to a function, paste the code of that function and the associated calls. 
  5. If applicable, mention what methods you’ve already used to solve the problem. This helps the AI learn and ensures it doesn’t suggest something you’ve already tried that turned out to be ineffective. 

“I tried binding the ‘handleChange’ to the class instance, but the error persists.”

  1. Specify your expectations – What is the outcome you’re trying to achieve that you can’t achieve right now because there’s an error in your code? 
  2. Encourage ChatGPT to gather information. Prompt the AI to ask you questions to ensure it has the full context before generating an answer. This enables the AI to fill any gaps in its knowledge. This prevents the AI from making up answers or drawing incorrect assumptions.

“Until you have enough context to generate a quality answer, ask me questions to fill in any knowledge gaps you may have.” 

  1. Ask for alternatives. ChatGPT’s first responses might not be the best. This is where you use your domain knowledge—and AI prompting skills—to guide the bot toward optimal input. (eg: “What if we used generators instead of lists?”). If the chatbot misunderstood something, provide further clarification. 

“You should generate several responses, filter them out, find the best ones, and merge them,” says Shahid. “The ones you don’t use can be a benchmark or reference for your learning.”

Crafting Coding Prompts for Refactoring and Optimization

Refactoring involves making changes to the codebase while keeping its functionality intact. Its purpose is to improve the integrity of the codebase to make it more readable and easy to maintain. This means removing redundancies and extraneous comments and using clear variables, functions, and class names. 

ChatGPT can provide suggestions to improve your codebase. Here’s how:

1. Describe the problem: Explain the specific code segment or part of the codebase that you want to refactor. Describe your issues, such as code complexity, duplication, or performance problems. Paste the code snippet. 

“I’m working on a software program for graphic designers, and we’re facing a performance issue with our graphic rendering algorithm. The rendering process is taking too long for complex graphics. How can we optimize the rendering performance?”

2. Ask for suggestions: Ask ChatGPT for suggestions on how to refactor the code to make it more maintainable, readable, and efficient. You can specify the type of refactoring you want, like simplifying a function, improving naming, or optimizing a specific algorithm.

“Could you provide suggestions on how to optimize the rendering performance of our graphic rendering algorithm? We want to speed up the process for complex graphics without sacrificing the output quality.”

3. Design patterns: If you’re considering implementing design patterns to improve your code structure, you can describe your current situation and ask ChatGPT for advice on which design pattern might be suitable and how to apply it.

“Could you recommend any design patterns commonly used in graphics rendering to enhance performance? How can we implement them effectively?”

4. Get naming suggestions: Naming conventions are crucial in code readability. If you’re struggling with choosing appropriate variable or function names, you can provide context to ChatGPT and ask for suggestions.

“Our rendering functions and variables are too convoluted. Can you suggest better names for the key functions and variables involved in the rendering algorithm? We want to improve readability and maintainability.”

5. Review code samples: Share relevant portions of your code with ChatGPT, and ask for feedback and suggestions on how to refactor that particular piece of code.

“I can provide a code snippet of our current rendering algorithm. Can you review it and suggest areas where we can refactor for better performance?”

6. Discuss trade-offs: Sometimes, refactoring decisions involve trade-offs between different aspects, such as performance, readability, and maintainability. ChatGPT can help you weigh these trade-offs and make informed decisions.

“We’re considering using a more optimized algorithm for rendering, but we’re worried it might make the code more complex. Can you help us understand the trade-offs between performance optimization and code complexity in this context?”

7. Analyze complexity: Describe your code’s complexity and ask for advice on simplifying it. ChatGPT can provide insights into breaking down complex functions or classes into smaller, more manageable parts.

“Our rendering algorithm has become quite complex, especially for intricate graphics. How can we break down the algorithm into smaller, more manageable parts while ensuring high-quality rendering?”

8. Testability and maintainability: Ask ChatGPT for recommendations on decoupling components, adding unit tests, and creating clear interfaces.

“As we optimize the rendering algorithm, we want to ensure it remains testable and maintainable. What strategies can we employ to ensure our changes don’t negatively impact these aspects?”

9. Prioritize refactoring tasks: If you have multiple areas in your codebase that need refactoring, you can discuss with ChatGPT which parts to tackle first based on their impact on the overall code quality.

“We have multiple rendering functions that need optimization. How can we prioritize which functions to tackle first to have the most impact on overall rendering performance?”

Wrapping Up

The evolution of AI in the realm of programming has undeniably revolutionized the way developers approach coding challenges. While AI tools offer a plethora of advantages, from code completion to error detection, the essence lies in crafting precise coding prompts. As we’ve explored, a well-structured prompt can be the difference between a generic code snippet and a tailored solution. As AI continues to shape the future of programming, mastering the art of effective prompting becomes paramount for developers aiming for excellence.

Since you’re here…
Curious about a career in data science? Experiment with our free data science learning path, or join our Data Science Bootcamp, where you’ll get your tuition back if you don’t land a job after graduating. We’re confident because our courses work – check out our student success stories to get inspired.

About Kindra Cooper

Kindra Cooper is a content writer at Springboard. She has worked as a journalist and content marketer in the US and Indonesia, covering everything from business and architecture to politics and the arts.