How to Use ChatGPT for Coding: Use Cases

Level Up Coding with ChatGPT — Use Cases for Developers

Level Up Coding with ChatGPT — Use Cases for Developers

In a galaxy far, far away…

As a developer, you have so many things on your plate. From coding and debugging to documentation and testing, the workload can be overwhelming at times. Perhaps, you’ve already tried to use ChatGPT (who hasn’t heard of it yet?!) to relieve the tension and get help with your day-to-day tasks. But how far have you gone with its use? And what side of AI Force would you take as a developer using the ChatGPT?

Would you take the Yoda route as an experienced and wise software developer using the Force of AI to your advantage? Or would you break bad and reveal an alter ego that will turn you to the dark side of the AI Force once you’ve just grasped the basics of coding?

We know that’s quite a tough one! But we are here to show you how you can make your life easier using ChatGPT. All without being lured to the dark side of AI. Which means overusing it and not relying on your own capabilities and skills.

May the Force be with you. As we are getting started.

First, What Exactly Is ChatGPT?

ChatGPT is a chatbot developed by OpenAI to interact with its users in a conversational way. It means that you can input a question or prompt, and the ChatGPT will respond to it. Then, you can continue the conversation back and forth. Just like chatting with a real person via messenger.

This is a sibling model of InstructGPT, a model trained to provide detailed responses, but with a few modifications. The initial model was improved with the help of human AI trainers who conducted conversations on both sides — as the user and AI assistant. The trainer’s suggestions and the InstructGPT dataset then were mixed to grow into a truly conversational model.

Learn the Limitations Before Using ChatGPT for Coding

While the capabilities of ChatGPT seem to be unlimited, in fact, it is not all-mighty. So, what limitations you may encounter when you start using it for app development? Here are the things the ChatGPT team mentions:

  • To err is… ChatGPT. — The chatbot may give nonsensical and incorrect answers since it knows how good code looks but doesn’t have a true understanding of code.
  • Sensitivity to tweaks. — As you slightly rephrase the request, you may get quite different results.
  • The guesswork. — Ideally, the model would ask clarifying questions if your request is vague. Now, it guesses what you meant, so you may get a vague or incomplete answer.
  • It’s all about updates. — The current version of GPT 3.5 was trained in early 2022 — a year ago. A lot of stuff could have happened within this period, causing the model to lag behind the recent industry standards.

How to Use ChatGPT As a Developer and Stay on The Good Side of the AI Force

First, here is when you should never use ChatGPT for coding. When generating code requires a lot of context, this chatbot will do little for you. You can’t share the entire codebase with it, so ChatGPT won’t be helpful in this case. Also, do not rely entirely on its answers as you learn how to code. The suggested code can be functional, but it may be verbose or too complex.

And now let’s see how the ORIL developers make the most out of the ChatGPT to streamline workflows and optimize the development experience.

Quick Prototyping

Rapid prototyping is a crucial part of the product development cycle. It allows companies to create functional product prototypes quickly, saving money and time. With the advent of conversational AI, in particular the introduction of ChatGPT, the quick prototyping process is going to take a huge leap forward.

The greatest perk of ChatGPT is that it quickly generates code snippets for prototypes or MVP products, speeding up the development and testing process. This way, you reduce the time and resources required to bring new products to market.

Would you like to learn more about product prototyping? We’ve crafted an article about prototypes for you

Example 1 — Creating a Basic React Component

Without any further ado, let’s see how the model works in action. For this purpose, we will create and style a login form component using React. So, here is the drill. You have to write a prompt and specify:

  • What type of code you want to get
  • What it should do
  • The tech stack and details
Generate a basic React component for a login form with username and password inputs. Style it with plain CSS. Use TypeScript. Use React Hook Form version 7. Fields are required.
import React, { useState } from "react";
import { useForm } from "react-hook-form";

interface FormData {
  username: string;
  password: string;
}

const LoginForm: React.FC = () => {
const {
  handleSubmit,
  formState: { errors },
  register,
  reset
} = useForm<FormData>({
    defaultValues: {
    username: "",
    password: ""
  }
});

const [formSubmitted, setFormSubmitted] = useState(false);

const onSubmit = (data: FormData) => {
  setFormSubmitted(true);
  console.log(data);
  reset();
};

return (
<form onSubmit={handleSubmit(onSubmit)}>
  <div>
    <label htmlFor="username">Username</label>
    <input
      id="username"
      type="username"
      placeholder="Email"
      {...register("username", { required: true })}
    />
    {errors.username?.type === "required" && (
    <p className="error-message">Username is required</p>
    )}
  </div>

  <div>
    <label htmlFor="password">Password</label>
    <input
      id="password"
      type="password"
      placeholder="Password"
      {...register("password", { required: true })}
    />
    {errors.password?.type === "required" && (
    <p className="error-message">Password is required</p>
    )}
  </div>
  <button type="submit">Submit</button>
  {formSubmitted && <p className="success-message">Form Submitted!</p>}
</form>
);
};

export default LoginForm;

 

As you see, the generated answer is pretty good. You get a form, controls, error messages, submit handler, and an interface. You can adjust it if needed.

Ok, we’re done with code generation. But can ChatGPT style it? Yes, it can. So, let’s create a prompt asking the model to style the written code. You can use the following scheme:

  • Ask what to do — to style the component (provide the component’s code)
  • Specify what design style you want to apply
Style this component with CSS. Print only CSS. Design style – material.

[your code here]

/* Form styles */
form {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
}

/* Input styles */
input {
  width: 100%;
  padding: 0.5rem;
  margin-bottom: 1rem;
  font-size: 1rem;
  border: none;
  border-bottom: 1px solid gray;
}

/* Label styles */
label {
  font-size: 1.2rem;
  margin-bottom: 0.5rem;
}

/* Submit button styles */
button[type="submit"] {
  background-color: #3f51b5;
  color: white;
  padding: 0.5rem 1rem;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 1.2rem;
  margin-top: 1rem;
}

/* Error message styles */
.error-message {
  color: red;
  font-size: 0.8rem;
  margin-top: 0.5rem;
}

/* Success message styles */
.success-message {
  color: green;
  font-size: 1rem;
  margin-top: 1rem;
}

 

Bravo, GPT. The code looks good. The AI model grasped the style we wanted to achieve. In particular, a material design. Below is the login form crafted by ChatGPT.

Example 2 — Creating A Docker File for Angular Application

Let’s ask AI to generate a Dockerfile for an Angular application

Generate a Dockerfile for an Angular application.
Here's a possible Dockerfile for an Angular application:

# Use an official Node.js runtime as a parent image
FROM node:14

# Set the working directory to /app
WORKDIR /app

# Copy the package.json and package-lock.json files to the container
COPY package*.json ./

# Install the dependencies
RUN npm install

# Copy the rest of the application files to the container
COPY . .

# Build the Angular app
RUN npm run build --prod

# Expose port 80 for the container
EXPOSE 80

# Start the Angular app using http-server
CMD [ "npx", "http-server", "-p", "80", "./dist" ]

This Dockerfile starts with an official Node.js runtime as the parent image. It sets the working directory to ‘/app’, copies the ‘package.json’ and ‘package-lock.json’ files to the container, installs the dependencies, and copies the rest of the application files to the container.

Then it builds the Angular app using the ‘npm run build –prod’ command, which creates a production build of the app. After that, it exposes port 80 for the container and starts the Angular app using ‘http-server’ on port 80.

You can build and run the Docker image using the following commands:

docker build -t my-angular-app .

docker run -p 80:80 my-angular-app

Note that the ‘my-angular-app’ tag can be any name you choose for the image. Also, the ‘-p 80:80’ option maps port 80 of the host machine to port 80 of the container.

While the generated code may require minor tweaking, you still get decent code snippets that cover your needs. Just make sure you give enough details.

We’ve provided only two ChatGPT applications for building quick prototypes. There are so many other things you can do with this model like generating:

  • query databases and optimizing queries
  • config files for a variety of tools
  • API endpoints, lambda functions
  • framework-specific entities (stores, controllers, services, etc.)
  • and much more

Learning and Upskilling

Among many other things, ChatGPT can teach you coding or help improve your skills. Since this is a conversational chatbot, you can get answers tailored to your needs by making clarifications as you make prompts. Here are some of the ways you may want to use ChatGPT for mastering your coding:

  • Asking general programming questions. — If you do not need to go deep into detail, you may make general tech inquiries like what Python is good for or what type of software can you develop with Flutter. Learn pros and cons of different programming languages, how to use specific frameworks or libraries, and more.
  • Generating code with explanations. — To learn new coding techniques and speed up code generation, you may ask the chatbot to write a specific code snippet and explain the fragments. It is handy if you’ve forgotten how to implement this or that function, so you will get hints in what direction to move.
  • Getting feedback and recommendations. — Are you not certain about the accuracy of the code you wrote? Ask ChatGPT to review it and show you the ways for its optimization.
  • Debating about the code. — Quite often truth springs from the argument. So, why not engage the ChatGPT in an interactive debate to boost your coding confidence and get familiar with new methods?!

So, let’s fancy you are new to React and you would like to know how to create an Angular-like service in React.

Create an Angular-like service for React, it should be a singleton.
Here is an example of a singleton service in React:

import React, { useState, useEffect } from 'react';

interface Data {
  data: string;
}

interface Service {
  data: Data;
  setData: (newData: Data) => void;
}

const ServiceContext = React.createContext<Service | null>(null);

const ServiceProvider: React.FC = ({ children }) => {
const [data, setData] = useState<Data>({ data: 'default' });

useEffect(() => {
  console.log('Service created');
  return () => {
    console.log('Service destroyed');
  };
}, []);

return (
  <ServiceContext.Provider value={{ data, setData }}>
    {children}
  </ServiceContext.Provider>
  );
};

const useService = (): Service => {
const service = React.useContext(ServiceContext);
if (!service) {
  throw new Error('Service provider not found');
}
  return service;
};

export { ServiceProvider, useService };

This implementation uses the ‘React createContext’ API to create a context for the service and a ‘ServiceProvider’ component that wraps the children and provides the context value. The context value is an object that holds the ‘data’ state and a ‘setData’ function to update it. The ‘useservice’ hook is used to access the service from other components. The service is a singleton because there is only one instance of the ‘ServiceProvider’ component created in the application and it is shared among all the components that use the service. The ‘usEffect’ hook is used to log when the service is created and destroyed to verify that there is only one instance.

Here we have a code snippet and explanations, which may be especially valuable to junior developers or those who are switching to new technology. You can go further and ask ChatGPT to show you how to use the generated code in the components.

Show me how to use useService and ServiceProvider from the previous answer.
Here's an example of how to use the ServiceProvider and useService from the previous answer in a React application:

import React from 'react';
import { ServiceProvider, useService } from './Service';

const ComponentA: React.FC = () => {
const { data, setData } = useService();

return (
  <div>
    <p>Component A</p>
    <p>Data: {data.data}</p>
    <button onClick={() => setData({ data: 'new data' })}>
      Update Data
    </button>
  </div>
);
};

const ComponentB: React.FC = () => {
const { data } = useService();
return (
  <div>
    <p>Component B</p>
    <p>Data: {data.data}</p>
  </div>
);
};

const App: React.FC = () => {
return (
  <ServiceProvider>
    <ComponentA />
    <ComponentB />
  </ServiceProvider>
);
};

export default App;

In this example, ‘ComponentA’ and ‘ComponentB’ are two components that use the service provided by ‘ServiceProvider’. The ‘useService’ hook is used to access the service from each component and the ‘setData’ function is used to update the data state in ‘ComponentA’. The ‘ServiceProvider’ component wraps both components and provides the service context. When the application is run, both components have access to the same instance of the service and the ‘data’ state can be updated from ‘ComponentA’ and reflected in ‘ComponentB’. The log statements from the ‘useEffect’ hook in the service implementation will show that there is only one instance of the service created.

If you would like to get more clarification on the suggested code, you can continue the conversation with the chatbot — just like with your tech buddy. We assume that, perhaps, ChatGPT has some limitations in the theoretical depth and may not be familiar with the latest updates. But, at a basic and documentation level, it’s more than enough to help you understand concepts you haven’t been familiar with before. And, what is important, saving you plenty of time.

Code Optimization

Do you often wrack your head around optimizing your code to meet specific requirements and standards? Have you already tried ChatGPT for this purpose? It’s a good idea to ask this chatbot to audit your script and ask for hints on its improvement.

Optimize this function and show complexity.

function multiplyAll(array) {
  let result = 1;

  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array[i].length; j++) {
      result *= array[i][j];
    }
  }

  return result;
}
The time complexity of the original function is O(n^2) because of the nested loop.

To optimize the function, we can eliminate one loop by using the Array.prototype.reduce() method:
function multiplyAll(array) {
  return array.reduce((acc, cur) => {
    return acc * cur.reduce((acc2, cur2) => acc2 * cur2, 1);
  }, 1);
}

This implementation has a time complexity of O(n).

It’s your call to consider ChatGPT suggestions or not. But one thing is clear — you get valuable code optimization hints in mere seconds.

Unit Tests

Writing unit tests can be tedious and time-consuming. Yet, it’s an essential part of a product development lifecycle because it allows you to minimize bugs in the code and ensure it does what you meant it to. So, let’s ask ChatGPT to write a unity test for the provided code snippet.

Write unit tests for code using Karma and Jasmine

function findMax(numbers) {
  return Math.max(...numbers);
}
Here's an example of unit tests for the findMax function using Karma and Jasmine:

describe("findMax", () => {
  it("should return the max number from an array of numbers", () => {
    const numbers = [1, 2, 3, 4, 5];
    const expectedResult = 5;

    const result = findMax(numbers);

    expect(result).toEqual(expectedResult);
  });

  it("should return the only number if the array has only one number", () => {
    const numbers = [5];
    const expectedResult = 5;

    const result = findMax(numbers);

    expect(result).toEqual(expectedResult);
  });

  it("should return the max negative number from an array of negative numbers", () => {
    const numbers = [-5, -4, -3, -2, -1];
    const expectedResult = -1;

    const result = findMax(numbers);

    expect(result).toEqual(expectedResult);
  });
});

ChatGPT gives you no excuses to skip writing unity tests. It does the job pretty well in most cases. Sure, it may not cover everything you may want to audit, but still, the unity test generated by ChatGPT is a good starting point.

Conclusion

These are just a few ways of using ChatGPT for coding. There is so much more you can do with this AI model. Use it as a smart code generator or a reliable assistant — it’s your call. After all, it will help you in your daily working routine and improve your performance.

Yet, do not forget to stick to the good side of the AI Force. Remember that it is just a Q/A tool that may help you in your day-to-day task, but won’t do the job for you. Use ChatGPT wisely and may the Force be with you.

AI in Logistics and Transportation Software

Artificial Intelligence (AI) is changing how we manage logistics and transport. It helps companies take fewer risks and spend less money on running their fleets. Now, more than 90% of companies are using AI or planning to improve how they handle their products and deliveries using the technology. If you want to fully tap into […]

Vitalii Lototskyi Avatar
Vitalii Lototskyi

4 Jan, 2024 · 5 min read

Prompt Engineering Tips

Prompt engineering is a cutting-edge approach to crafting effective and efficient conversational AI systems. In an age where human-computer interactions are becoming increasingly prevalent, mastering the art of prompt engineering is vital. This article delves into the principles, strategies, and best practices behind prompt engineering. What is prompt engineering? Prompt engineering is crafting carefully structured […]

Ihor Sokolyk Avatar
Ihor Sokolyk

3 Oct, 2023 · 8 min read

Spring Boot With ChatGPT

ChatGPT stands out as one of the most robust language models available today. It’s capable of generating texts that closely resemble human-like conversation and can perform tasks such as translation and summarization, among other functionalities. This makes ChatGPT a preferred choice among developers and businesses seeking to enhance their AI capabilities. That’s why we’re here […]

Ihor Kosandyak Avatar
Ihor Kosandyak

28 Sep, 2023 · 4 min read