5 ways to use ChatGPT as a software developer

5 ways to use ChatGPT as a software developer

ChatGPT is a variant of the GPT-3 language model developed by OpenAI, specifically designed for conversational language processing tasks. It is trained on a large dataset of human-generated chat messages and is able to generate appropriate responses to a given prompt in a conversational style. I believe ChatGPT is rather an opportunity to make our time-consuming and sometimes boring tasks somehow automated and more efficient as a software developer. I collected 5 ways to use this AI tool as a supporter to be more efficient.

Writing wiki pages and tutorials

Effective documentation is essential for the success of any software project. It helps new team members become productive more quickly and ensures that all team members are following the same processes. ChatGPT can assist with this task by generating a customizable template for your project’s documentation. Its conversational style allows for the creation of a more personalized result, saving time and effort in the long run.

I requested the ChatGPT to generate Readme for NextJS project. “Generate Readme template for Typescript NextJS project” After the initial response, I asked ChatGPT to modify the npm commands to yarn by stating “Change npm to yarn, please”. Finally, I requested the addition of a section on deploying the project to Vercel by saying “Add a section about deploying the NextJS project to Vercel”. One of the standout features of ChatGPT is its ability to retain context throughout the conversation, allowing for short instructions to be given for any necessary changes.

Solve algorithmic problems faster

As a developer, you may occasionally encounter algorithmic challenges that require the implementation of mathematical formulas or complex algorithms. In these situations, it can be helpful to seek guidance from resources like Stack Overflow or to diagram concepts and flows. ChatGPT can also be a valuable tool in these situations, thanks to its conversational style. If you need to make modifications to an algorithm, simply provide a brief description of the desired changes and ChatGPT can assist with the rest.

As an example, consider the task of calculating Fibonacci numbers. By providing a summary of the desired algorithm to ChatGPT (e.g., “I need a TypeScript function that calculates the Fibonacci sequence recursively”), it is possible to receive a response with the necessary code. If the initial request is not fully understood, it may be necessary to clarify or adjust the specifications. For instance, if the returned function only calculates the Fibonacci number for a single input, the request could be revised to ask for a sequence of Fibonacci numbers instead. In this way, ChatGPT can assist with modifying the algorithm as needed, without the need for additional explanation. The result function:

export function fibonacci(n: number): number[] {
  if (n === 0) {
    return [];
  }
  if (n === 1) {
    return [0];
  }
  if (n === 2) {
    return [0, 1];
  }

  const sequence = fibonacci(n - 1);
  sequence.push(sequence[sequence.length - 1] + sequence[sequence.length - 2]);
  return sequence;
}

The tool is great but I suggest not copy-paste solutions blindly because it is not necessarily perfect. Always review the results and write tests to make sure the code gives the right results. Speaking of tests, ChatGPT also can help generate test cases.

Write unit tests

Writing unit tests is a crucial aspect of building complex applications. While it can be a tedious task, ChatGPT can help streamline the process and improve the precision of your tests. By leveraging artificial intelligence, ChatGPT can generate tests for a wide range of scenarios, allowing you to more thoroughly and efficiently verify the functionality of your code.

If you wish to ensure the accuracy of the recursive Fibonacci function through unit testing, you can utilize ChatGPT to generate test cases. Simply request test cases for the function using the conversational style of the chat (“Write unit tests for the recursive Fibonacci function.”), and ChatGPT will provide you with a set of test cases that cover a variety of scenarios. In this case, ChatGPT has generated four unit test cases that will allow you to verify the performance of the function under different conditions.

import { fibonacci } from './fibonacci';

describe('fibonacci', () => {
  it('should return an empty array for n = 0', () => {
    expect(fibonacci(0)).toEqual([]);
  });

  it('should return [0] for n = 1', () => {
    expect(fibonacci(1)).toEqual([0]);
  });

  it('should return [0, 1] for n = 2', () => {
    expect(fibonacci(2)).toEqual([0, 1]);
  });

  it('should return the correct Fibonacci sequence for n > 2', () => {
    expect(fibonacci(3)).toEqual([0, 1, 1]);
    expect(fibonacci(4)).toEqual([0, 1, 1, 2]);
    expect(fibonacci(5)).toEqual([0, 1, 1, 2, 3]);
  });
});

Okay, this is great, although I noticed the function doesn’t handle negative inputs. By requesting that ChatGPT extend the test cases and the code to include negative input values, you can ensure that the function is robust and able to handle a wider range of scenarios. Let’s request ChatGPT to extend the test cases and the code with this scenario. “Extend the test cases with one more test case where the input is a negative number and extend the function to handle negative values properly.” ChatGPT is able to effectively extend both the test cases and the function to accommodate this additional requirement, even without explicit instructions on how to handle negative values.

...
it('should handle negative input properly', () => {
    expect(fibonacci(-1)).toEqual([]);
    expect(fibonacci(-2)).toEqual([]);
    expect(fibonacci(-3)).toEqual([]);
 });
...
function fibonacci(n: number): number[] {
  if (n <= 0) {
    return [];
  }
  ...
}

It is important to keep in mind that ChatGPT is a tool that can assist with the development of code and test cases, but it does not actually execute the tests against the code. Therefore, it is necessary to manually run the tests and verify the results to ensure that the generated code and test cases are accurate. While ChatGPT is able to provide valuable assistance, it is possible for mistakes to occur, either in the test code or in the algorithm code. Therefore, it is always advisable to double-check the output and carefully review the results to ensure the accuracy and reliability of your code.

It helps to understand code snippets

As a developer, a key part of your job is to understand and work with code, which can sometimes be challenging when encountering unfamiliar algorithms or patterns. In these situations, ChatGPT can be a useful resource for gaining a better understanding of a particular code block. For example, if you are unfamiliar with certain libraries or concepts, such as Axios or refresh tokens, ChatGPT can help you understand the purpose and function of this code part. Simply provide ChatGPT with the code block in question and request an explanation, and the AI will do its best to provide a clear and comprehensive understanding of the algorithm.

let isRefreshing = false;
let failedQueue = [];

const processQueue = (error, token = null) => {
  failedQueue.forEach(prom => {
    if (error) {
      prom.reject(error);
    } else {
      prom.resolve(token);
    }
  })

  failedQueue = [];
}

const interceptor = (axiosInstance) => (error) => {
    const _axios = axiosInstance;
    const originalRequest = error.config;

    if (error.response.status === 401 && !originalRequest._retry) {

        if (isRefreshing) {
            return new Promise(function(resolve, reject) {
            failedQueue.push({resolve, reject})
            }).then(token => {
            originalRequest.headers['Authorization'] = 'Bearer ' + token;
            return _axios.request(originalRequest);
            }).catch(err => {
            return Promise.reject(err);
            })
        }

        originalRequest._retry = true;
        isRefreshing = true;

        const refreshToken = window.localStorage.getItem('refreshToken') || 'refresh123xyz';
        return new Promise((resolve, reject) => {
        window.api.auth.refresh(refreshToken)
            .then(({data}) => {
                window.localStorage.setItem('token', data.token);
                window.localStorage.setItem('refreshToken', data.refreshToken);
                _axios.defaults.headers.common['Authorization'] = 'Bearer ' + data.token;
                originalRequest.headers['Authorization'] = 'Bearer ' + data.token;
                processQueue(null, data.token);
                resolve(_axios(originalRequest));
            })
            .catch((err) => {
                processQueue(err, null);
                reject(err);
            })
            .then(() => { isRefreshing = false })
        })
    }

    return Promise.reject(error);
};

export default interceptor

I asked ChatGPT, “Can you describe what does this code do?”

One of the unique features of ChatGPT is that it is a chat-based AI tool, rather than a one-purpose algorithm. This allows it to offer a more flexible and versatile range of capabilities, as you can interact with it in a more natural and conversational manner. For example, rather than simply providing a single output or solution, you can engage in a dialogue with ChatGPT and request more specific or detailed information. This can be particularly useful when seeking to gain a deeper understanding of a particular concept or issue. Overall, the chat-based nature of ChatGPT makes it a powerful and useful resource for a wide range of tasks and purposes.

This is actually quite impressive, the chat can not only decode the functionality to plain nglish but also can help understand deeply the aspects of the algorithm. Once you have a solid understanding of the code, you can then request that ChatGPT generate documentation to help other developers quickly understand the code as well. Overall, ChatGPT’s combination of explanation and documentation capabilities makes it a useful tool for improving your understanding of complex code and algorithms.

Writing Twitter threads, blog posts, articles, essays

It can often be challenging to organize and articulate one’s thoughts when writing a post or article. While ChatGPT can provide helpful structure and ideas, it is important to remember that the quality and authenticity of your writing should always be the primary focus. Simply copy-pasting information from the internet is not the goal; rather, the value of your writing comes from your own thoughts and experiences. That being said, ChatGPT can serve as a useful tool for generating initial ideas and helping to give shape to your writing. It is always advisable to carefully review and refine the output from ChatGPT to ensure that it aligns with your own ideas and style of writing. Let’s see an example:

And writing further:

One of the useful features of ChatGPT is its ability to rephrase sentences and adjust the tone of a paragraph. This can be helpful when you are seeking to find the right tone for your writing or want to make your writing more professional. By simply requesting that ChatGPT rephrase a particular sentence or paragraph, you can alter the tone and style of your writing while maintaining the essence of your original message.

Conclusion

There has been much discussion about the potential impact of AI on software development and other fields, with some expressing concern that these technologies may eventually replace human workers. While it is true that AI solutions like ChatGPT can be very useful in assisting with software development tasks, it is important to recognize that these tools are not yet perfect and may make mistakes. It is therefore essential to carefully review and validate the output from ChatGPT and other AI tools, rather than blindly copying and pasting the results. In this way, AI can serve as a valuable resource for improving efficiency and streamlining workflows, rather than replacing the need for human expertise and judgment. Ultimately, the goal should be to use AI as a complement to human skills and capabilities, rather than a replacement.