paint-brush
ChatGPT in Software Engineering: A Glimpse Into the Futureby@vgukasov
2,665 reads
2,665 reads

ChatGPT in Software Engineering: A Glimpse Into the Future

by Vladislav GukasovFebruary 10th, 2023
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

Chatbots have revolutionized how we interact with technology, providing instant and automated responses to our queries. OpenAI's GPT-3 has further enhanced this technology, allowing chatbots to understand and respond to natural language inputs in a human-like manner. ChatGPT can significantly enhance software engineers' productivity and efficiency.
featured image - ChatGPT in Software Engineering: A Glimpse Into the Future
Vladislav Gukasov HackerNoon profile picture

Chatbots have revolutionized how we interact with technology, providing instant and automated responses to our queries.


The development of large language models such as OpenAI's GPT-3 has further enhanced this technology, allowing chatbots to understand and respond to natural language inputs in a human-like manner.


From code generation and debugging assistance to technical knowledge and best practices, ChatGPT can significantly enhance software engineers' productivity and efficiency.


Through this article, I want to delve into how ChatGPT can support the software development lifecycle and provide a glimpse into the future of human-AI collaboration in software engineering.

What Can ChatGPT do for Software Engineers?

I decided to ask ChatGPT directly about its possibilities.


Me: How can you help in software engineering?


ChatGPT: “As a language model, I can assist in various aspects of software engineering such as:


  1. Code generation and automation of repetitive tasks


  2. Providing technical information and best practices on programming languages, algorithms, design patterns, and architecture.


  3. Suggesting solutions to coding problems and debugging issues.


  4. Generating explanations and summaries of complex technical concepts.


Note: I'm an AI language model and while I can provide information and suggest solutions, I can't actually implement or execute any code.”


Let’s try each bullet point out to see if ChatGPT can help us in software engineering.

Code Generation and Automation of Repetitive Tasks

Code generation and automation of repetitive tasks are critical aspects of software development that aim to streamline the development process and reduce the time and effort required for coding repetitive parts of a software project.


Whether creating CRUD operations or generating HTML templates, ChatGPT can help reduce development time and improve overall efficiency, freeing developers to focus on other essential aspects of the project.


I asked ChatGPT to generate CRUD operations for a table in MySQL using Golang and sqlx library.


Me: I have a MySQL table:

create table users
(
    id   varchar(36) PRIMARY KEY NOT NULL,
    email varchar(50),
    password varchar(255),
    created_at timestamp default CURRENT_TIMESTAMP ,
    updated_at timestamp default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
);


Write the Golang code that implements CRUD operations over the table using sqlx. Each method should be implemented as a separate function that accepts ctx context.Context and User structure or ID.


ChatGPT:

package main

import (
	"context"
	"fmt"

	"github.com/jmoiron/sqlx"
	_ "github.com/go-sql-driver/mysql"
)

type User struct {
	ID        string `db:"id"`
	Email     string `db:"email"`
	Password  string `db:"password"`
	CreatedAt string `db:"created_at"`
	UpdatedAt string `db:"updated_at"`
}

func connectToDb() (*sqlx.DB, error) {
	db, err := sqlx.Open("mysql", "user:password@tcp(localhost:3306)/dbname")
	if err != nil {
		return nil, err
	}
	return db, nil
}

func createUser(ctx context.Context, user User) error {
	db, err := connectToDb()
	if err != nil {
		return err
	}
	defer db.Close()

	_, err = db.ExecContext(ctx, "INSERT INTO users (id, email, password) VALUES (?, ?, ?)", user.ID, user.Email, user.Password)
	if err != nil {
		return err
	}
	return nil
}

func readUser(ctx context.Context, id string) (User, error) {
	var user User

	db, err := connectToDb()
	if err != nil {
		return user, err
	}
	defer db.Close()

	err = db.GetContext(ctx, &user, "SELECT * FROM users WHERE id=?", id)
	if err != nil {
		return user, err
	}
	return user, nil
}

func updateUser(ctx context.Context, user User) error {
	db, err := connectToDb()
	if err != nil {
		return err
	}
	defer db.Close()

	_, err = db.ExecContext(ctx, "UPDATE users SET email=?, password=?, updated_at=CURRENT_TIMESTAMP WHERE id=?", user.Email, user.Password, user.ID)
	if err != nil {
		return err
	}
	return nil
}

func deleteUser(ctx context.Context, id string) error {
	db, err := connectToDb()
	if err != nil {
		return err
	}
	defer db.Close()

	_, err = db.ExecContext(ctx, "DELETE FROM users WHERE id=?", id)
	if err != nil {
		return err
	}
	return nil
}

The code is not designed perfectly. For example, we shouldn't reconnect to the database with each query due to the overhead. Also, errors should be wrapped in fmt.Errorf()


However, ChatGPT wrote the entire boilerplate code that we can make a few modifications to. Therefore, ChatGPT passed this part of the examination, and we can go to the next bullet point.

Providing Technical Information

ChatGPT claimed it could provide technical information and best practices on programming languages, algorithms, design patterns, and architecture. So I asked it to advise me on an approach to solving a problem.


Me: I have a TypeScript app. There is a task to implement different payment methods in the app. How should I implement it?


ChatGPT: One way to implement different payment methods in your TypeScript app is to use the Strategy design pattern. Here's how you can do it:


  1. Create an interface that defines the payment method:
phpCopy codeinterface PaymentMethod {
  processPayment(amount: number): void;
}
  1. Create classes for each payment method that implement the interface:
typescriptCopy codeclass CreditCard implements PaymentMethod {
  processPayment(amount: number): void {
    console.log(`Paying ${amount} using credit card.`);
  }
}

class PayPal implements PaymentMethod {
  processPayment(amount: number): void {
    console.log(`Paying ${amount} using PayPal.`);
  }
}
  1. Create a class that uses the payment method interface:
typescriptCopy codeclass Order {
  private paymentMethod: PaymentMethod;

  setPaymentMethod(paymentMethod: PaymentMethod) {
    this.paymentMethod = paymentMethod;
  }

  processOrder(amount: number) {
    this.paymentMethod.processPayment(amount);
  }
}
  1. Use the payment method in your app:
scssCopy codeconst order = new Order();
order.setPaymentMethod(new CreditCard());
order.processOrder(100);

order.setPaymentMethod(new PayPal());
order.processOrder(100);


In this example, the Order class can process payments using different payment methods. The payment method can be changed dynamically at runtime by calling the setPaymentMethod method. The client code doesn't need to know the specifics of how payments are processed, it only needs to know that it can use the processOrder method to process payments.


I prefer to use the Factory pattern here instead of the Strategy pattern because, in that case, we also abstract the logic of building a specific payment method.


I asked ChatGPT if it had another idea about a design pattern that could fit here.


Me: Is there another pattern that can fit here?


ChatGPT: Yes, another pattern that could fit here is the Factory pattern. The Factory pattern allows you to create objects without specifying the exact class of the object that will be created. You can use the Factory pattern to create different payment methods based on a specific type or configuration. Here's an example:


This time it showed me what I expected to see. Indeed, both design patterns are applicable here, and choosing one will depend on your project and needs. But the undoubtful thing is ChatGPT could suggest different good design patterns for a problem.


We've checked the design patterns. Next, let's review how ChatGPT can handle issues in a code.

Suggesting Solutions to Coding Problems

Software engineers solve coding problems daily. However, code debugging is the most time-consuming process, and using an AI helper would be a good performance boost.


I faced an issue and asked ChatGPT how to fix that.


Me: I have a function that encrypts text with the AES256 algorithm. The problem is that an encrypted string contains invalid UTF-8 characters. How can I fix it?


func (c *Cipher) Encrypt(plainText []byte) []byte {
	plainText = pkcs7Padding(plainText, aes.BlockSize)

	cipherText := make([]byte, aes.BlockSize+len(plainText))
	copy(cipherText[:aes.BlockSize], c.iv)

	mode := cipher.NewCBCEncrypter(c.block, c.iv)
	mode.CryptBlocks(cipherText[aes.BlockSize:], plainText)

	return cipherText
}


ChatGPT: The issue of invalid UTF-8 characters can be resolved by encoding the encrypted text as a base64 string before returning it. This will ensure that the resulting string only contains characters from the ASCII range, which are valid UTF-8 characters.


To encode the encrypted text as a base64 string, you can use the base64.StdEncoding.EncodeToString function in Go:


func (c *Cipher) Encrypt(plainText []byte) string {
	plainText = pkcs7Padding(plainText, aes.BlockSize)

	cipherText := make([]byte, aes.BlockSize+len(plainText))
	copy(cipherText[:aes.BlockSize], c.iv)

	mode := cipher.NewCBCEncrypter(c.block, c.iv)
	mode.CryptBlocks(cipherText[aes.BlockSize:], plainText)

	return base64.StdEncoding.EncodeToString(cipherText)
}

Base64 is a way to represent binary data as a string of characters. Of course, there are other ways to do that, for instance, Hex encoding, but in our case, base64 has advantages over them:


  • Compactness: it uses a smaller number of characters to represent the same amount of data compared to hex encoding. This can be useful in situations where the encoded data size needs to be kept to a minimum.


  • Readability: it uses a more compact character set (A-Z, a-z, 0-9, +, /) that is easier to read and less prone to mistakes than hex encoding.


  • Ease of use: it’s built into many programming languages and is widely used for encoding binary data in internet protocols such as email, HTTP, and XML. As a result, libraries and functions are often available to encode and decode base64 data efficiently.


Therefore, for me, ChatGPT’s answer is reasonable. Next, let’s ask about some complex technical concepts.

Generating Explanations of Complex Technical Concepts

This is a fascinating feature for curious engineers. You can explore the technology world in-depth with ChatGPT. And the learning path will look like a dialog with a teacher.


I asked ChatGPT about one of the consensus algorithms with one follow-up question. Let’s take a look.


Me: Explain the RAFT consensus algorithm for a 10-year-old kid?


ChatGPT: RAFT is a way for computers to agree on something together. Imagine you have a group of friends and you want to decide on what to do for the day.


In RAFT, each friend is like a computer and you choose one friend to be the leader. The leader makes a suggestion, like "let's go to the park".


Then, all the other friends vote on whether they agree with the leader's suggestion. If most of them agree, then the group decides to go to the park. But if not enough friends agree, the leader tries another suggestion.


This way, all the friends work together to make a decision, and everyone is happy with what they are doing. That's what RAFT does, but with computers instead of friends.


Me: How do the computers elect a leader?


ChatGPT: In RAFT, the computers elect a leader by holding an election. Each computer gets a chance to run for leader by sending out a message to all the other computers saying, "I want to be the leader."


Then, all the computers count the votes, and the computer with the most votes becomes the leader. If there is a tie, then the computers will have another election to break the tie.


The important thing is that only one computer can be the leader at a time, and if the leader computer stops working, the other computers will hold another election to choose a new leader. This way, the group always has a leader and can continue making decisions together.


I could keep asking follow-up questions about leader election algorithm internals, and I would always have an answer.


The example shows how we can start exploring new things from high-level basics and dive into the depths as far as we need.

Conclusion

I’ve been using ChatGPT in my daily routine for weeks. This tool is worth considering for software engineers of any grade. It helped me with a wide range of problems, from code debugging to designing complex system architecture.


Therefore, ChatGPT is a valuable asset to software engineers in various aspects of their work.


The integration of ChatGPT into the software development process can result in faster and more efficient development cycles, improved code quality, and a better overall software engineering experience.

References

  1. ChatGPT (https://openai.com/blog/chatgpt/)