4 Effortless Tricks to Improve Your Code with ChatGPT

It is widely acknowledged that ChatGPT has gained significant recognition in the field, so let us proceed directly to the valuable techniques I have discovered through my extensive experience as a programmer, which I diligently apply in my everyday coding endeavors.

1. Generate code for languages I’m not familiar with

It is a prevalent practice in software development projects to utilize multiple programming languages. When working with C++, for instance, it is often necessary to employ additional languages such as CMake, Bash, Python, and others. However, it is quite common to use these auxiliary languages for specific tasks and subsequently overlook them.

This approach proves particularly advantageous for C++ projects, as the initial setup process in CMake can be intricate and time-consuming. In situations where a simple configuration is all that is needed to initiate a project, employing this technique can save valuable time and effort.

ChatGPT output for the question: "Generate a CMake project"

By adopting this approach, I am able to initiate a project promptly without the need to comprehend the intricacies of CMake or its usage. This significantly reduces the time required for project setup, enabling me to dive into coding swiftly.

Another language that has proven immensely valuable is Bash. However, working with Bash sometimes necessitates an extensive understanding of the language itself as well as the Linux operating system. This dependency can be mitigated by leveraging the capabilities of ChatGPT. For instance, consider the following example where I require a quick method to obtain a list of all process IDs (PIDs) that are currently running, and subsequently remove a specific process by providing an input parameter.

2. Explain code

In the software development realm, it is not uncommon to encounter scenarios where we need to delve into pre-existing legacy code, whether they were generated for us or by other individuals. As time goes by, it becomes increasingly challenging to comprehend code that we ourselves wrote in the distant past. This difficulty amplifies when dealing with external code. However, ChatGPT excels in its ability to provide comprehensive explanations of code. Let’s consider the following code snippet:

int randomNumber = Random::get<int>(0, std::numeric_limits<int>::max());
// current date/time based on current system
std::time_t now = std::time(0);

// convert now to string form
std::string time = std::asctime(std::localtime(&now));
std::string title("Simulations/Simulation" + std::to_string(randomNumber) +".csv");
std::ofstream stream(title);
csv2::Writer<csv2::delimiter<','>> writer(stream);

This is the depth explanation:

3. Comment code

Generating meaningful and concise comments for code can often be a tedious and challenging task. It requires careful consideration of how other programmers who read the code will comprehend it accurately. Thankfully, ChatGPT can assist in automating this process. Let’s continue with the previous code snippet and ask ChatGPT to generate meaningful comments for it:

// Generate a random number
int randomNumber = Random::get<int>(0, std::numeric_limits<int>::max());

// Get the current system time
std::time_t now = std::time(0);

// Convert the time to a string
std::string time = std::asctime(std::localtime(&now));

// Create the file name for writing the CSV data
std::string title("Simulations/Simulation" + std::to_string(randomNumber) + ".csv");

// Open the file for writing
std::ofstream stream(title);

// Create a CSV writer for the file
csv2::Writer<csv2::delimiter<','>> writer(stream);

4. Improve code

Setting personal ego aside, it is a common occurrence for programmers to find themselves needing to make quick implementations to meet deadlines or due to the desire for efficiency. In such situations, ChatGPT proves to be highly valuable as it excels in improving code in ways that may not have been initially considered by the programmer.

The following code snippet is extracted from a personal project TwitchLootClicker that it is a Google Chrome extension in Javascript. Javascript is an easy language to pick up quickly but I am not very familiar with so I tend to code like if I still using C++:

function millisToMinutesAndSeconds(millis) {
    if(millis < 0){
        return "Ready to claim";
    }
    var minutes = Math.floor(millis / 60000);
    var seconds = ((millis % 60000) / 1000).toFixed(0);
    return minutes + ":" + (seconds < 10 ? '0' : '') + seconds;
}

function millisToHoursMinutesAndSeconds(millis){
    var seconds = (millis / 1000).toFixed(0);
    var minutes = Math.floor(seconds / 60);
    var hours = "";
    if (minutes > 59) {
        hours = Math.floor(minutes / 60);
        hours = (hours >= 10) ? hours : "0" + hours;
        minutes = minutes - (hours * 60);
        minutes = (minutes >= 10) ? minutes : "0" + minutes;
    }

    seconds = Math.floor(seconds % 60);
    seconds = (seconds >= 10) ? seconds : "0" + seconds;
    if (hours != "") {
        return hours + "h " + minutes + "m " + seconds + "s";
    }
    return minutes + "m " + seconds + "s ";
}

function minutesToMilliseconds(minutes){
    return (minutes * 60000);
}

The first function serves to convert milliseconds to the format of minutes and seconds (MM:SS). The second function converts milliseconds to the format of hours, minutes, and seconds (HH:MM:SS). Lastly, the third function converts minutes to milliseconds.

Introducing the next prompt to ChatGPT: “Refactor this code using idiomatic JavaScript conventions.” The goal of this prompt is to modify the code to adhere to the standard programming practices followed by JavaScript developers.

/**
 * Converts milliseconds to minutes and seconds
 * @param {number} millis - The time value in milliseconds
 * @returns {string} The formatted time in "minutes:seconds" format
 */
function millisToMinutesAndSeconds(millis) {
  if (millis < 0) {
    return "Ready to claim";
  }

  const minutes = Math.floor(millis / 60000);
  const seconds = Math.floor((millis % 60000) / 1000).toString().padStart(2, '0');
  return `${minutes}:${seconds}`;
}

/**
 * Converts milliseconds to hours, minutes, and seconds
 * @param {number} millis - The time value in milliseconds
 * @returns {string} The formatted time in "hours:h minutes:m seconds:s" format
 */
function millisToHoursMinutesAndSeconds(millis) {
  const seconds = Math.floor(millis / 1000);
  const minutes = Math.floor(seconds / 60);
  let hours = "";

  if (minutes > 59) {
    hours = Math.floor(minutes / 60).toString().padStart(2, '0');
    minutes %= 60;
  }

  const formattedMinutes = minutes.toString().padStart(2, '0');
  const formattedSeconds = (seconds % 60).toString().padStart(2, '0');

  if (hours !== "") {
    return `${hours}h ${formattedMinutes}m ${formattedSeconds}s`;
  }

  return `${formattedMinutes}m ${formattedSeconds}s`;
}

/**
 * Convert minutes to milliseconds
 * @param {number} minutes - The time value in minutes
 * @returns {number} The equivalent time value in milliseconds
 */
function minutesToMilliseconds(minutes) {
  return minutes * 60000;
}

Those are the improvements done by ChatGPT to the former code:

  • Added type annotations to the function parameters for better code documentation.
  • Used template literals (“) for string concatenation, making the code more readable.
  • Replaced the toFixed() method with Math.floor() and toString().padStart() to ensure consistent formatting and avoid floating-point errors.
  • Used the const keyword for variables that don’t require reassignment.
  • Made the code more concise and eliminated unnecessary variable assignments.