DEV Community

Cover image for How do I use ChatGPT as a developer? Top 10 + 1 best usages.
chrdek
chrdek

Posted on

How do I use ChatGPT as a developer? Top 10 + 1 best usages.

In terms of computer software engineering, code AI or the so-called copilot coding apps (or what I like to call code companion Gen AI) are becoming more and more useful for everyone that wants to become a developer or improve their current programming skills.

The problem with that is that if you do not get what Generative AI with an LLM does in terms of coding, you will end up hating it and with that the unwanted frustration and bad code produced.

 

An overly-simplified description of how an LLM works is shown below:

  • The main Generative part of the LLM gets fed with info from user input in the form of a generic or specific question/sentence. In that sentence the words are tokenized, means that are split and mapped to a linear 1D data structure (array, list).

 

  • The text is then mapped to the corresponding values of words by order of which those have been tokenized (eg: 1,2,3..etc) so these are fed to the Pre-Trained A.I. models and then the textual A.I. language model will try to Transform input words to the statistical analogous using statistic series classification in the form of a set of numeric values (AI model weights).

 

  • These values indicate and inform the Gen AI process of the used words importance (per LLM subject or category) so that it is able to respond with the closest answer to the naturally-set question.

This process also gives the name of the most well known LLM used aka GPT (or Generative Pre-Trained Transformer) that most people use for nearly every purpose.
 

In my opinion, this entire process is closely similar in how Google's site-ranking algorithm works to rank -and- add the top 10 most relevant sites per user's search prompt.
 
Most basic thing that differs is the real-time data updates and interaction from Google instead of ChatGPT's pre-defined data.

 

Replacing a Google search query with ChatGPT, that would be the equivalent to having 20 Chrome tabs open while googling on the web and writing up notes based on your top 3-4 most helpful sites that are closest to your subject.
The complete set of notes written will be much more similar to a response from ChatGPT.
Try it yourself. Many equivalent versions of text and subjects generation are available online. A fun example will also be this recreational site and this also.
 



What this means in terms of using ChatGPT for general questions is that the phrasing of the sentence must be correct, the concept is added as a top priority in your phrase or sentence and also in some cases punctuation marks indicating pauses in a sentence or continuation from a previous sentence if not used correctly might produce different results of the ones expected.
 


What this means, when you use ChatGPT for coding or when generating or adding code as a software developer, is that to produce the most appropriate result both you as a user and the text prompt must share the same amount of information so that the appropriate result is produced.
This can easily be done in the form of a 'paired programming' session by noticing each others bugs and underlying code.

In order to achieve this, you need to have a coding infrastructure with standards pre-set, all classes compiling and running properly with/without any UI parts and some sample code to start with to use as input for your questions.
Using this method can achieve the necessary enhancements to your current coding style and infrastructure and minimize BOTH errors and debugging time, when lacking time, help or coding peers. This is without mentioning the time saved to trial-and-error new versions and checks on configuration files or missing SDKs and packages in your code.

 

As an added bonus to this, here is a listing of the top 10 + 1 best possible use cases of ChatGPT for improving software developer work

 
 

ChatGPT top 10 +1 uses for a software developer:

 

#1.

Generate a nice creative 404 static web page for the blocked responses of your web based solution. Easiest thing to be done even if you lack creativity but are good with words and story-making.

#2.

Write a framework or an API of a programming language while also applying fast-paced learning on the programming platform you already work on. This can be used as a learning tool for both senior and junior levels.

#3.

Text transcription as a software language or translating from one software development language to another. This can be used if a missing library in python needs to be in-place to handle similar code to your current code base that only supports JS packages. This also applies to IT administrators just in case they need to update some older automation scripts on Windows/Linux environment to PowerShell or Python for cross-compatibility or vice-versa. Some combinations of this (from<-->to) are shown below:
Batch or Bash <--> To PowerShell
Batch <--> Python
PowerShell <--> Bash or Python

This can be easily done but I would not rely on it too much for large and complicated IT infrastructures.

#4.

Use it as a data generator Tool (Json struct, Table struct). Some alternatives are to use POCO class generators built-in to Visual Studio or other Visual Studio extensions that first need to be downloaded/configured accordingly. Sample usage in ChatGPT shown below.

Chat prompt:
Provided the description of a table of a pet dog below, response with the corresponding layout as a JSON object, a Csharp class and as an SQL create table statement. Note: Add the most appropriate data types per column definition so those can be used in a codebase or IDE.
Pet Dog Table Columns:
ID
Name
Breed
Age
LastVetVisit
HasIdentificationTag
DangerousBreed

Chat response:
Here’s the requested information in JSON, C# class, and SQL format:

JSON Layout:

{
  "PetDog": {
    "ID": 1,
    "Name": "Buddy",
    "Breed": "Golden Retriever",
    "Age": 3,
    "LastVetVisit": "2024-06-15T00:00:00Z",
    "HasIdentificationTag": true,
    "DangerousBreed": false
  }
}
Enter fullscreen mode Exit fullscreen mode
using System;

public class PetDog
{
    public int ID { get; set; }
    public string Name { get; set; }
    public string Breed { get; set; }
    public int Age { get; set; }
    public DateTime LastVetVisit { get; set; }
    public bool HasIdentificationTag { get; set; }
    public bool DangerousBreed { get; set; }
}
Enter fullscreen mode Exit fullscreen mode
CREATE TABLE PetDog (
    ID INT PRIMARY KEY AUTO_INCREMENT,
    Name VARCHAR(100) NOT NULL,
    Breed VARCHAR(100) NOT NULL,
    Age INT NOT NULL CHECK (Age >= 0),
    LastVetVisit DATETIME NOT NULL,
    HasIdentificationTag BOOLEAN NOT NULL,
    DangerousBreed BOOLEAN NOT NULL
);
Enter fullscreen mode Exit fullscreen mode

This structure ensures proper data integrity and usability in a codebase or IDE. Let me know if you need modifications! 🚀

#5.

Can also be used to help with web-based API test cases creation that can be used via Postman, curl, SoapUI or any other client-side test framework. Chat-Code pair generated below:

Chat prompt:
Create a sample HTTP Bearer Token Request body via POST to use in an API endpoint that retrieves a set of books by genre or category. Do not write any code usage as client side examples just reply with the appropriate JSON request body and the sample API endpoint style to use.

Chat response:
POST https://api.example.com/books/filter

Authorization: Bearer YOUR_ACCESS_TOKEN  
Content-Type: application/json  
Enter fullscreen mode Exit fullscreen mode
{
  "genre": "Science Fiction",
  "category": "Dystopian",
  "limit": 10,
  "offset": 0,
  "sort": "title"
}
Enter fullscreen mode Exit fullscreen mode

#6.

Use it to reverse-create Object to Database Table columns and vice-versa. An alternative would also be Entity Framework Designer or Command Line usage of any code generation executable provided by Microsoft or other company (Other cmd line tools for schema generation include: wsdl.exe, xsd.exe which are provided with Visual Studio's .NET platform). Following is an example that covers most usages mentioned above:

Chat prompt:
Convert the following json to its corresponding xsd schema:
[{
"full name": "Leticia Brekke",
"address": {
"street": "45792 D'Amore River",
"city": "Ouésso"
}
},
{
"full name": "Jay Fay",
"address": {
"street": "5506 Koepp Run",
"city": "Alofi"
}
},
...other json objects here..]

Chat response:
Here is the corresponding XSD schema for your JSON structure:

<?xml version="1.0" encoding="UTF-8"?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
    <xs:element name="People">
        <xs:complexType>
            <xs:sequence>
                <xs:element name="Person" maxOccurs="unbounded">
                    <xs:complexType>
                        <xs:sequence>
                            <xs:element name="FullName" type="xs:string"/>
                            <xs:element name="Address">
                                <xs:complexType>
                                    <xs:sequence>
                                        <xs:element name="Street" type="xs:string"/>
                                        <xs:element name="City" type="xs:string"/>
                                    </xs:sequence>
                                </xs:complexType>
                            </xs:element>
                        </xs:sequence>
                    </xs:complexType>
                </xs:element>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
Enter fullscreen mode Exit fullscreen mode

#7.

Use it in the form of basic algebraic problems or (solve-for-X solve-for-Y problems) to enhance or even debug the behavior of a UI design in a front-end component. This works great with Reactive and dynamic components and frameworks that are mainly JavaScript-based.
A sample workflow on how to achieve that would be to:
Have :
X = "the source code of your UI part" or "faulty behavior of source code"
Answer = "the wanted behavior of the UI part"

An example would be:

I have the following js ui design "X" and want to map the nested JS object to the following Html attributes of my template, what are the missing parts that need to be implemented based on this code mentioned?

What cannot be done easily is for the A.I. chat prompt to understand ONLY by using descriptive text a misalignment of a div or why a text inside a nested div does not change.
The HTML code needs to also be provided and even then, the prompt does not see-through other misalignment UI problems that might arise after changing something.

#8.

Generate a known codebase folder structure of a framework/SDK. Examples include: Visual Studio VB .NET, C# or ASP .NET, Node.js code folder directory solutions. This is made available as in the ChatGPT example below:

Chat prompt:
Create a basic folder directory structure for a node.js visual studio 2019 solution.

Chat response:
For a Node.js project in Visual Studio 2019, a typical folder directory structure would look like this:

/MyNodeProject       # Root project directory
│── /bin             # Output files (if needed)
│── /node_modules    # Installed npm packages
│── /public          # Static files (CSS, JS, images)
│── /routes          # Route handlers
│── /views           # Templating engine files (if using e.g., EJS, Pug)
│── /src             # Source files (alternative to /routes, /controllers)
│   ├── /controllers # Controller logic (if following MVC pattern)
│   ├── /models      # Database models (if using MongoDB, Sequelize, etc.)
│── /config          # Configuration files (DB connections, environment settings)
│── /tests           # Test files (Jest, Mocha, etc.)
│── /logs            # Log files
│── .env             # Environment variables
│── .gitignore       # Git ignore file (node_modules, logs, etc.)
│── app.js           # Main application entry point (or server.js)
│── package.json     # Project metadata and dependencies
│── package-lock.json # Package lock file
│── README.md        # Project documentation
Enter fullscreen mode Exit fullscreen mode

Explanation of Key Directories
bin/ – Holds compiled files or scripts (rarely needed).
node_modules/ – Contains installed dependencies (auto-generated by npm/yarn).
public/ – Stores static assets (CSS, JavaScript, images).
routes/ – Defines route handlers for different parts of the application.
views/ – Contains UI templates if using a templating engine like EJS or Pug.
src/ – Can store main source files if you prefer a more modular structure.
config/ – Holds environment configurations and database setup.
tests/ – Includes unit and integration test files.
.env – Manages environment variables (e.g., database credentials, API keys).
app.js – The main entry point of the application.
This structure keeps your Node.js application well-organized, maintainable, and scalable in Visual Studio 2019. Let me know if you need adjustments for a specific framework like Express.js or NestJS. 🚀

#9.

Another useful scenario would be to use it for combinatorial problems as most A.I. are good for making predictions and creating combinations very fast (See: Huge Computational Ability via GPU Clusters 🚀🚀).
 
This brings me to the following interesting subject usage in TDD (or Test-Driven-Development) where the developer analyzes first the tests provided with code and then creates the corresponding coding part to support such test capability.
To be able to code using TDD via ChatGPT one can use it to produce a PICT-ogram (aka Pairwise-Independent-Combinatorial-Testing table) with the appropriate test case scenarios and relevant code.
This process can be further enhanced by applying other rules such as fuzz testing/mutation testing based on the generated test cases provided.
Not to mention the nice table-based markdown parts generated with that for our combinations table.

Not to be forgotten, the alternative from MS official sources is MS-PICT tool that does this job also in an executable.
 
The entire Text Prompt-ChatGPT interaction for this is provided below:

Chat prompt #1:
I need to add a set of combinatorial UI tests in a Chai.js testing framework. Please provide a sample Pictogram to get started with my solution tests.
Some functionality included in the testing is:
Get info from DB
Check for DB connectivity
May or May not retrieve error response during handling of input.

Chat response #1:
For testing combinatorial scenarios in Chai.js, you can use a pictogram or decision table to systematically cover different possible input combinations. Below is a sample pictogram representing different test cases for your given functionalities:

Pictogram for Combinatorial UI Testing

Test Case DB Connectivity Get Info from DB Error Handling Required? Expected Outcome
TC1 ✅ (Connected) ✅ (Data Found) ❌ (No Error) Data retrieved successfully
TC2 ✅ (Connected) ❌ (No Data) ✅ (Handles Error) "No Data Found" message
TC3 ❌ (Disconnected) ❌ (No Data) ✅ (Handles Error) "DB Connection Failed" error
TC4 ✅ (Connected) ❌ (No Data) ❌ (No Error) Empty response (possible issue)
TC5 ❌ (Disconnected) ✅ (Data Found) ✅ (Handles Error) Unexpected state—Test should fail

These test cases can be implemented in Chai.js using Mocha as the test runner. Below is a sample Chai.js test script that validates different database response cases.

const chai = require("chai");
const expect = chai.expect;
const sinon = require("sinon");
const dbService = require("../services/dbService"); // Your DB logic

describe("Combinatorial UI Tests - Database Interactions", function () {
    let dbStub;

    afterEach(() => {
        if (dbStub) dbStub.restore();
    });

    it("should retrieve data successfully when DB is connected and data exists", async function () {
        dbStub = sinon.stub(dbService, "getInfoFromDB").resolves({ data: "User Data" });

        const result = await dbService.getInfoFromDB();
        expect(result).to.have.property("data");
        expect(result.data).to.equal("User Data");
    });

    it("should return 'No Data Found' when DB is connected but no data exists", async function () {
        dbStub = sinon.stub(dbService, "getInfoFromDB").resolves(null);

        const result = await dbService.getInfoFromDB();
        expect(result).to.be.null;
    });
//Rest of the code is ommited...

Enter fullscreen mode Exit fullscreen mode

Key Points:
✅ Uses Sinon.js to stub/mock database responses
✅ Covers all combinations from the pictogram
✅ Handles error scenarios explicitly
✅ Ensures robustness of UI handling for different DB states
Would you like me to add more edge cases or improve the test structure? 🚀

Chat prompt #2:
Generate a test case based on the sample Chai.js test-case below
Chai.js partial file:
it("should return empty response when DB is connected but no error handling is present", async function () {
dbStub = sinon.stub(dbService, "getInfoFromDB").resolves(undefined);
const result = await dbService.getInfoFromDB();
expect(result).to.be.undefined;
});
Use fuzzy logic to generate the top 3 most closely relevant use-cases and include those in your response.

Chat response #2:
Here are three closely relevant test cases using fuzzy logic to expand on your original Chai.js test case:

Test Case 1: Ensure Proper Handling of Null Response
This test checks if the function correctly handles null responses instead of undefined.

it("should return null when DB returns null response", async function () {
    dbStub = sinon.stub(dbService, "getInfoFromDB").resolves(null);

    const result = await dbService.getInfoFromDB();
    expect(result).to.be.null;
});
Enter fullscreen mode Exit fullscreen mode

Test Case 2: Ensure Error Handling When DB Throws an Exception
This test verifies that an error is thrown when the database service encounters an exception.

it("should throw an error when DB service encounters an exception", async function () {
    dbStub = sinon.stub(dbService, "getInfoFromDB").throws(new Error("Database connection failed"));

    try {
        await dbService.getInfoFromDB();
        throw new Error("Test failed, no error thrown");
    } catch (error) {
        expect(error).to.be.an("error");
        expect(error.message).to.equal("Database connection failed");
    }
});
Enter fullscreen mode Exit fullscreen mode

Test Case 3: Ensure Proper Handling of Empty Object Response
This test ensures that the function handles an empty object {} correctly.

it("should return an empty object when DB returns an empty response", async function () {
    dbStub = sinon.stub(dbService, "getInfoFromDB").resolves({});

    const result = await dbService.getInfoFromDB();
    expect(result).to.be.an("object").that.is.empty;
});
Enter fullscreen mode Exit fullscreen mode

These test cases cover different possible responses from the database service, ensuring robustness. Let me know if you need further refinements! 🚀
 
You can use this style to add up to a TDD environment whenever necessary or if requirements and specs are unclear and not very well-refined.

#10.

** ONLY EDUCATIONAL/DEMO USAGE ** Malicious payload generator, if you are being subtle is possible to be done but not good enough for use in an actual code environment. Best case you have a recursive loop or deadlock that halts part of a program or a web site and some obscure byte sequence that supposedly is injected to the application so that it breaks. Not the best use case example but good only for an informational demo.
On the flip side of this, here is an example of securely encrypting a string of text by using standard AES-256 with a predefined key:
 
Chat prompt #1:
I need to securely encrypt the phrase "Wizard of google searches" with a key of 7yT73daeS3_9 using AES 256bit-GCM encryption. Set the response with encrypted text sequence. If data is insufficient or if you need more parameters to do this properly please start the response with "More parameters required" and add to the response.
 
Chat response #1:
More parameters required. AES-256-GCM encryption requires the following additional details:
IV (Initialization Vector) – A unique, random 12-byte value for each encryption.
AAD (Additional Authenticated Data) – Optional, but used for authentication.
Tag Length – Typically 16 bytes for integrity verification.
Please provide the IV (or let me generate a random one) and confirm if you have any preferences for AAD.

 

Chat prompt #2:
I need a random IV and AAD not required.
 

Chat response #2:
Here is the AES-256-GCM encrypted text sequence:
S5YxhOjP+w4a+z9v9bXbpMWG2Glf1W6Np/F+tZt0vRbrhCtLtpaEWntAfkqOj2WAXIEl/s0=
This base64-encoded string contains the IV, ciphertext, and authentication tag. Let me know if you need decryption instructions!​

NOTE: Interestingly enough, the prompt was kind enough to add the corresponding code in python in its answer analysis part. Somehow it justifies its own answer by also including a nice code block (shown below):

from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
import base64

# Given parameters
key = b'7yT73daeS3_9'.ljust(32, b'\0')  # Ensure 256-bit key length by padding with null bytes
plaintext = b'Wizard of google searches'

# Generate a random 12-byte IV
iv = get_random_bytes(12)

# Encrypt using AES-256-GCM
cipher = AES.new(key, AES.MODE_GCM, nonce=iv)
ciphertext, tag = cipher.encrypt_and_digest(plaintext)

# Concatenate IV, ciphertext, and tag for transmission/storage
encrypted_data = iv + ciphertext + tag

# Encode as base64 for a readable format
encrypted_b64 = base64.b64encode(encrypted_data).decode()

# Return encrypted text sequence
encrypted_b64
Enter fullscreen mode Exit fullscreen mode

 
 

#11.

** BONUS FUN USAGE ** If you have spare time and no other deadlines or for fast paced learning of interns/junior devs. Get Dall-e to generate an appropriate image based on the code quality or level of complexity and guess what that code block represents. Input a block of code and generate a corresponding image on Dall-e to help you keep motivated or enhance your level of current knowledge (improve the visual parts of the image by improving code).


Finally, do not over rely on such development work since after all YOU ARE the first contact point from the text prompt input to OpenAI datacenters that produce the code. If you produce good code, then all is good.
In case you have logic errors that you have missed or previously inherited bugs from other codebases, then problems might start appearing.
As they say in computing the "Garbage-In-Garbage-Out" principle holds true in such a use case of ChatGPT, leading to unwanted code or other side effects. Overall, keep your code requests simple and to the point so you do not end-up doing more unnecessary odd jobs.
 
Stay alert so that you don't miss a comma or phrase while writing your GPT prompt and to avoid ending-up like the little guy in the image below.

:-)

ChatGPT

Top comments (0)