DEV Community

Hroney
Hroney

Posted on

Utilizing Generative AI for Coding Questions

Using Generative AI to Best Edit and Utilize for Coding-Related Questions


Index

  • Introduction
  • Why use Generative AI for Coding
  • Best practices
    • Starting Off
    • Scope
    • Clear Context
    • Sharing Relevant code snippets
    • State clear objectives
    • Highlight errors and issues
    • Ask Targeted Questions
    • Include Input and Output
    • Use Comments
  • Examples of Effective AI utilization
    • Debugging a Flask Route
    • Optimizing a React Component
  • Conclusion

Introduction

We've now been living with generative AI's for nearly 2 years. It's here to stick around and I've grown accustomed to utilizing it for all manner of questions. I'd like to share with you today the required skillset for getting the information you want using your acumen to discern good and proper answers.

Resources used: Chatgpt 3.5, 4, and Perplexity.ai

This will blog post will be centered around coding but following this ruleset will allow you to tease out the proper information from a generative AI.

Why Use Generative AI for Coding?

Generative AI's save time. Quick solutions to coding problems if given the right context. They are a great learning tool. My background is in education with a focus on pedagogy. Hiring and training tutors is what I'm good at, utilizing these AI tools to mold them into good tutors is essential to understanding how to get the answers you need.
These AI tools are also fantastic for debugging - Stuck on a logical problem? They can offer a solution or, if you don't want an outright solution, suggestions on how to approach the topic to allow for the learner/user to remain in that zone of proximal development.

Best Practices for Utilizing AI in Coding

Starting off

Be nice to your AI :) Say please an thank you (Or at least I will, should be lose the technology arms race against our binary counterparts I wish to have been known as Cordial).

Following a simple speaking and presenting pattern can help you sum most of what I'll say. This may look familiar to a lot of you:

  • Tell'em what you're going to tell'em.
    • Start off by telling the AI the outcome you want from your problem
  • Tell'em
    • Give the AI the context of the problem (code, math problem, etc.)
  • Tell'em what you told'em
    • Summarize your requirements be adding additional specific context on how you want the problem presented to you (As code, as an answer, as an outline, etc)

Scope

It's important to share code snippets and not your entire code base. You can share your code base as context for something like Add comments to my code or provide a read me. But limiting your scope of questioning will ensure good answers more often and maintains your personal autonomy to know how the code is developed. Asking an AI tool to write you code will only have you endlessly error handling and playing catch-up. Instead, write what you can - ask for help when you must.

Please fix the bug in this component **[provide snippet]** it's not doing **[XYZ]** is a much better query than Here's my code **[entire code-base]**. Why isn't it working?

Provide Clear Context

  • Starting off, every query to a generative AI needs clear context. Context on what you're attempting to accomplish or want to get out of the exchange.
  • Example:

    I am working on a web application that manages tutoring sessions using Flask and React.
    

The above gives the AI context on which areas to focus: flask, React, Web application, POST all give the AI the groundwork on where to build out THEIR context on how to share information. Since we've put in flask and React the answers delivered back to you will be entirely centered around these context languages and framework (Javascript, Python, etc.)

Share Relevant Code Snippets

  • After establishing where the groundwork is with context, you need to next provide the Tell'em. Give the context of the code in question.
  • Example:

    @app.route('/sessions', methods=['POST'])
    def create_session():
        data = request.get_json()
        new_session = Session(
            tutor_id=data['tutor_id'],
            tutee_id=data['tutee_id'],
            start_time=data['start_time'],
            end_time=data['end_time']
        )
        db.session.add(new_session)
        db.session.commit()
        return jsonify(new_session.to_dict()), 201
    

State Clear Objectives

  • Clarify what you want to achieve with the code. It's important to explain to the AI the outcome that you want. This is all part of the process on getting back relevant answers.

  • Example:

    I want to add validation to ensure that the session times do not overlap for the same tutor.
    

Make note It's important to know that you will often get 'wrong' answers. It will at first be hard to discern what a 'wrong' answer looks like. Thus, you will need to be at the very least comfortable with discerning WHAT an issue looks like. As my dad would call it - your BS meter needs to be good at sniffing out potential problems. Knowing your vocabulary, data structures, and what the input / output of your components is, will better help you maintain code autonomy.

Highlight Errors or Issues

  • Next, provide context on what is happening negatively to your snippet (If you so desire)

  • Example:

    Currently, the code does not check for overlapping session times, which can lead to scheduling conflicts.
    

Ask Targeted Questions

  • Be specific in your queries to get precise answers. The AI tools are just that, tools. They can't read your mind (yet). Give them an actionable command.
  • Example:

    How can I modify this route to check for overlapping sessions before creating a new one?
    

Include Input and Output

  • Provide sample input and expected output to help the tool understand WHAT is going through the modules/components. It not only provides better and more context (Keyword of the day!) it also helps you maintain that code autonomy I've been mentioning all over the blog.
  • Example:

    Sample Input: {"tutor_id": 1, "tutee_id": 2, "start_time": "2024-06-11T10:00:00", "end_time": "2024-06-11T11:00:00"}
    Expected Output: {"error": "Session times overlap for the same tutor."}
    

Use Comments

  • Highlight specific parts of the code you are unsure about using comments. Your comments add extra context WITHIN the query. They pinpoint the problem for the AI tools to better target where you believe the issue may lit.
  • Example:

    # This is where I need to check for overlapping sessions
    

Examples of Effective AI Utilization

Example 1: Debugging a Flask Route

I'm working on a Flask web application, and I'm encountering an error in one of my routes. I'm using Flask for the backend and React for the frontend. The specific route causing the issue is /api/get_data.
Here's the code snippet for the route that's causing the problem:

# This is the route for retrieving data from the database
@app.route('/api/get_data', methods=['GET'])
def get_data():
    # Some code here that's causing the error
    return jsonify(data)
Enter fullscreen mode Exit fullscreen mode

I need help identifying and fixing the error in this route so that it returns the expected data when accessed.
The error I'm encountering seems to be related to a KeyError when accessing a dictionary in the route function. I'm not sure why this error is occurring.
Can you help me identify what might be causing the KeyError in this route function? Any suggestions on how to fix it?

Example 2: Optimizing a React Component

I'm working on a React project, and I've noticed that one of my components is rendering slowly. The component in question is a dashboard displaying real-time data, and it's impacting the overall performance of the application.
Here's the code snippet for the component that's rendering slowly:

// Dashboard Component: Renders real-time data
import React from 'react';

const Dashboard = () => {
    // Component code here
    return (
        <div>
            {/* Dashboard content */}
        </div>
    );
}

export default Dashboard;
Enter fullscreen mode Exit fullscreen mode

I'm looking for suggestions on how to optimize this component's performance to improve rendering speed and overall application performance.
The main issue I'm encountering is that the dashboard component takes a long time to render, especially when fetching and displaying large amounts of real-time data.
What are some best practices for optimizing React components, particularly those that render real-time data? Are there any specific techniques or libraries I should consider using?

Conclusion

Generative AI is a tool like any other - skilled wielders will be able to utilize the tool to a much greater effect. Knowing your subject area allows you to better focus the AI to get the answers you want. As such, Anyone can ask a Generative AI to write a webpage, but not everyone can then take that code to style it, deploy it, expand on it, change it to the customers wishes, etc.

Following the above practices will give your AI the best Context for understanding and providing you with the best answer or at least one you can adapt.

I'd love to hear about your journeys with AI tools and how you have learned to best prompt them for information

Top comments (0)