Back to overview

ChatGPT for software developers.

▼ Post information

Author Jef Meijvis Publish date 11/01/2023
Title ChatGPT for software developers. Id 8
Source 008-chatgpt-as-a-developer.md Render timestamp Dec 06, 2023, 06:08:31 AM (GMT+1)
Views 55 Tags openai, chatgpt, dotnet
Author Jef Meijvis
Publish date 11/01/2023
Title ChatGPT for software developers.
Id 8
Source 008-chatgpt-as-a-developer.md
Render timestamp Dec 06, 2023, 06:08:31 AM (GMT+1)
Views 55
Tags openai, chatgpt, dotnet
opengraph

▼ Table of contents

Share this post:

ChatGPT

ChatGPT

ChatGPT is a powerful chatbot developed by OpenAI that can generate human-like text. It is based upon the GPT-3 family of large language models. As a software developer, you can use ChatGPT to automate repetitive tasks, generate code, and even help with documentation. In this blog post, we'll explore some of the ways ChatGPT can help you as a developer, and how you can get started using it. The practical examples shown here will make use of C# as its programming language.

OpenAI logo

Image: OpenAI logo

Accessing ChatGPT

The browser chat interface of ChatGPT can be accessed via chat.openai.com. Authorization can be done via a Google or Microsoft account. After logging in you can start interacting with the chatbot by asking it a question in the chatbox.

For example, the query Write a method in C# that calculates the median price out of a list of products. returns the following result:

Interacting with the chatbot via its web interface

Image: Interacting with the chatbot via its web interface

Generating code

Lets imagine we have a simple User class as shown below. Each user has a name, and a list of friends, which are also Users.

Code snippet

1
class User
2
{
3
    public string Name { get; set; }
4
    public List<User> Friends { get; set; }
5
}

If we want to create some kind of utility logging function to log information about a specific user, we can ask ChatGPT to generate this for us after first pasting the class code in the chatbox. Query:

Could you create a method that prints out the summary of this user class for an instance?

ChatGPT came up with the following method:

Code snippet

1
public void PrintUserSummary(User user)
2
{
3
    Console.WriteLine($"Name: {user.Name}");
4
    Console.WriteLine("Friends:");
5
    if (user.Friends == null || !user.Friends.Any())
6
    {
7
        Console.WriteLine("No friends found.");
8
    }
9
    else
10
    {
11
        foreach (var friend in user.Friends)
12
        {
13
            Console.WriteLine($"- {friend.Name}");
14
        }
15
    }
16
}

Converting code

Let's continue with our User example, and write a method that double links the friends.

Code snippet

1
void LinkFriends(User user)
2
{
3
    for (int i = 0; i < user.Friends.Count; i++)
4
    {
5
        User friend = user.Friends[i];
6
        if (!friend.Friends.Contains(user))
7
            friend.Friends.Add(user);
8
    }
9
}

Perhaps we would like to see this method written in Linq. Query: Could you convert this code to make use of Linq?

And ChatGPT will convert the method just as we asked:

Code snippet

1
void LinkFriends(User user)
2
{
3
    user.Friends.Where(friend => !friend.Friends.Contains(user)).ToList().ForEach(friend => friend.Friends.Add(user));
4
}

I won't go into the discussion about whether or not Linq makes is more or les readable, but as you can see it get's properly converted.

Changing the language

Let's convert the method we initially created to Typescript. Query: could you convert this piece of code to typescript?

Code snippet

1
function linkFriends(user: User) {
2
    user.friends.forEach(friend => {
3
        if (!friend.friends.includes(user)) {
4
            friend.friends.push(user);
5
        }
6
    });
7
}

Helping with Documentation

Lets say we encountered the above code in a wild codebase, and we could not figure out what it exactly does. Let's ask ChatGPT:

Explaining a piece of code

Image: Explaining a piece of code

Unit tests

Lets imagine the follwing setup. We have a User class, a mockable IKeyValueStore interface and a Save and Load method. We want to test these two methods.

Code snippet

1
void SaveUser(User user, IKeyValueStore store)
2
{
3
    store.Set(user.Name, user.Age.ToString());
4
}
5

6
User LoadUser(string name,IKeyValueStore store)
7
{
8
    int age = int.Parse(store.Get(name));
9
    User u = new User();
10
    u.Age = age;
11
    u.Name = name;
12
    return u;
13
}
14

15
interface IKeyValueStore
16
{
17
    void Set(string key, string value);
18
    string Get(string key);
19
}
20

21
class User
22
{
23
    public string Name { get; set; }    
24
    public int Age { get; set; }
25
}

Let's ask ChatGPT to generate some unit tests for us.

Code snippet

1
[Test]
2
public void SaveUser_ValidInput_SavesUserInStore()
3
{
4
    // Arrange
5
    var store = new MemoryKeyValueStore();
6
    var user = new User { Name = "John", Age = 30 };
7

8
    // Act
9
    SaveUser(user, store);
10

11
    // Assert
12
    Assert.AreEqual(user.Age.ToString(), store.Get(user.Name));
13
}
14

15
[Test]
16
public void LoadUser_ValidInput_LoadsUserFromStore()
17
{
18
    // Arrange
19
    var store = new MemoryKeyValueStore();
20
    var user = new User { Name = "John", Age = 30 };
21
    store.Set(user.Name, user.Age.ToString());
22

23
    // Act
24
    var loadedUser = LoadUser(user.Name, store);
25

26
    // Assert
27
    Assert.AreEqual(user.Age, loadedUser.Age);
28
    Assert.AreEqual(user.Name, loadedUser.Name);
29
}
30

31
[Test]
32
public void LoadUser_InvalidInput_ThrowsArgumentException()
33
{
34
    // Arrange
35
    var store = new MemoryKeyValueStore();
36
    var invalidKey = "InvalidKey";
37

38
    // Act and Assert
39
    Assert.Throws<ArgumentException>(() => LoadUser(invalidKey, store));
40
}

While these aren't perfect, they give us a good indication and baseline to start improving these testcases.

Creating a new language!

Let's try to invent a new language called JefSpeak. First we must declare some rules:

JefSpeak is a new programming language. It resembles C#, but there are a few changes:

  • a method declaration follows the following syntax: 'method' returntype methodname|arguments|
  • the 'void' return type doesn't exist anymore, as it is replaced with 'nothing'
  • the int type is replaced with number
  • above each method name there is an automatically generated comment block that explains the function of each parameter
  • the '=' assignment operator is replaced with the word 'is'
  • the '+' addition operator is replaced with the word 'and'
  • the Console.Write() method is replaced is with say

Then we can ask it to convert a C# codeblock to this newly invented language. Could you convert the following piece of code to JefSpeak?

Code snippet

1
void Fibonacci(int len)
2
{
3
    int a = 0, b = 1, c = 0;
4
    Console.Write("{0} {1}", a, b);
5
    for (int i = 2; i < len; i++)
6
    {
7
        c = a + b;
8
        Console.Write(" {0}", c);
9
        a = b;
10
        b = c;
11
    }
12
}

And we get the following result:

Code snippet

1
method nothing Fibonacci|number len|
2
// This function prints out the first len Fibonacci numbers
3
{
4
    number a is 0, b is 1, c is 0;
5
    say "{0} {1}", a, b;
6
    for (number i is 2; i < len; i++)
7
    {
8
        c is a and b;
9
        say " {0}", c;
10
        a is b;
11
        b is c;
12
    }
13
}

What's even beter, is that our chat session now has knowledge of the concept of JefSpeak. This means that from now on we can start asking questions about this new 'language'. Let's have a look and see how we could calculate the median out of a list of numbers in JefSpeak:

Code snippet

1
method number Median|list of number numbers|
2
// This function calculates the median of a given list of numbers
3
{
4
    numbers.sort();
5
    number len is numbers.length;
6
    if(len % 2 == 0)
7
    {
8
        number median is (numbers[len/2 - 1] and numbers[len/2]) / 2;
9
        return median;
10
    }
11
    else
12
    {
13
        number median is numbers[(len - 1) / 2];
14
        return median;
15
    }
16
}

Well that's looks like an awful and unwieldy language. But it is a fun experiment to showcase ChatGPT's transformative capabilities nonetheless.

Conclusion

In conclusion, ChatGPT is an incredibly powerful tool that can help software developers automate repetitive tasks, generate code, and even help with documentation. It can save you a significant amount of time and effort, allowing you to focus on more complex tasks and improve the overall efficiency of your work. With easy integration and access to the model, it is worth giving it a try in your next project. However keep in mind that AI assisted tools can be wrong, while their response might seem really solid and confident.

Alternatives

An interesting alternative to check out might be Github Copilot, which can intergrate right in your IDE. It is also developed in part by OpenAI.

Further reading

Back to top