Refactoring code is the process of restructuring existing code without changing its behavior. The benefits of refactoring include improving code readability, reducing complexity, making the code easier to maintain, and allowing new features to be added more easily.
This article gives you some ideas for using Copilot to refactor code in your IDE.
Note
Example responses are included in this article. GitHub Copilot Chat may give you different responses from the ones shown here.
Alternatively, if you already know that existing code, like the example bash script, is inefficient:
Select either the for loop or the entire contents of the file.
Open inline chat:
In VS Code: Press Command+i (Mac) or Ctrl+i (Windows/Linux).
In Visual Studio: Press Alt+/.
In JetBrains IDEs: Press Control+Shift+i (Mac) or Ctrl+Shift+g (Windows/Linux).
Type optimize and press Enter.
Copilot suggests revised code. For example:
find . -type f -name "*.txt" -execwc -l {} +
This is more efficient than the original code, shown earlier in this article, because using -exec ... + allows find to pass multiple files to wc at once rather than calling wc once for each *.txt file that's found.
Assess Copilot's suggestion and, if you agree with the change:
In VS Code and Visual Studio: Click Accept.
In JetBrains: Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).
As with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.
Avoiding repetition will make your code easier to revise and debug. For example, if the same calculation is performed more than once at different places in a file, you could move the calculation to a function.
In the following very simple JavaScript example, the same calculation (item price multiplied by number of items sold) is performed in two places.
let totalSales = 0;
let applePrice = 3;
let applesSold = 100;
totalSales += applePrice * applesSold;
let orangePrice = 5;
let orangesSold = 50;
totalSales += orangePrice * orangesSold;
console.log(`Total: ${totalSales}`);
You can ask Copilot to move the repeated calculation into a function.
Select the entire contents of the file.
Open inline chat:
In VS Code: Press Command+i (Mac) or Ctrl+i (Windows/Linux).
In Visual Studio: Press Alt+/.
In JetBrains IDEs: Press Control+Shift+i (Mac) or Ctrl+Shift+g (Windows/Linux).
Type: move repeated calculations into functions and press Enter.
Copilot suggests revised code. For example:
functioncalculateSales(price, quantity) {
return price * quantity;
}
let totalSales = 0;
let applePrice = 3;
let applesSold = 100;
totalSales += calculateSales(applePrice, applesSold);
let orangePrice = 5;
let orangesSold = 50;
totalSales += calculateSales(orangePrice, orangesSold);
console.log(`Total: ${totalSales}`);
Assess Copilot's suggestion and, if you agree with the change:
In VS Code and Visual Studio: Click Accept.
In JetBrains: Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).
As with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.
Large methods or functions that perform multiple operations are likely to offer fewer opportunities for reuse than smaller, simpler functions that are focused on performing a particular operation. They may also be more difficult to understand and debug.
Copilot can help you to split up complex blocks of code into smaller units that are more suitable for reuse.
The following Python code is a very simple example, but it shows the principle of splitting up a single function into two functions that perform particular operations.
import pandas as pd
from pandas.io.formats.style import Styler
defprocess_data(item, price):
# Cleanse data
item = item.strip() # Strip whitespace from item
price = price.strip() # Strip whitespace from price
price = float(price) # Convert price to a float# More cleansing operations here# Create and print a DataFrame
data = {'Item': [item], 'Price': [price]}
df = pd.DataFrame(data)
print(df.to_string(index=False))
# Example usage
item = " Apple "
price = " 1.25"
process_data(item, price)
To split up the process_data function:
Put the cursor in the function name.
Open inline chat:
In VS Code: Press Command+i (Mac) or Ctrl+i (Windows/Linux).
In Visual Studio: Press Alt+/.
In JetBrains IDEs: Press Control+Shift+i (Mac) or Ctrl+Shift+g (Windows/Linux).
Type: split into 2 separate functions: one for cleansing data, the other for printing and press Enter.
Copilot suggests revised code. For example:
defcleanse_data(item, price):
# Cleanse data
item = item.strip() # Strip whitespace from item
price = price.strip() # Strip whitespace from price
price = float(price) # Convert price to a floatreturn item, price
defprint_data(item, price):
# Create and print a DataFrame
data = {'Item': [item], 'Price': [price]}
df = pd.DataFrame(data)
print(df.to_string(index=False))
defprocess_data(item, price):
item, price = cleanse_data(item, price)
print_data(item, price)
Note
The example suggestion shown above replaces the existing function with three functions. The third function simply calls the other two functions, and allows for existing code that calls the process_data function.
Assess Copilot's suggestion and, if you agree with the change:
In VS Code and Visual Studio: Click Accept.
In JetBrains: Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).
As with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.
There are often several ways to write code that does, or does not, get executed depending on various conditions. Some conditional structures are better suited than others to particular use cases, and choosing an alternative conditional structure can sometimes make the code easier to read.
This Java method uses a series of if and else if statements to determine which operation to perform:
A switch statement might be a better way of applying the same logic.
Put the cursor in the method name.
Open inline chat:
In VS Code: Press Command+i (Mac) or Ctrl+i (Windows/Linux).
In Visual Studio: Press Alt+/.
In JetBrains IDEs: Press Control+Shift+i (Mac) or Ctrl+Shift+g (Windows/Linux).
Type: rewrite the condition to use a switch and use Java 21 syntax with null case, but also add documentation and provide a better function name.
This demonstrates how you can use a single prompt to ask Copilot to make multiple changes.
Press Enter.
Copilot suggests revised code. For example:
/**
* Retrieves the sound made by a given animal.
*
* @param animal The name of the animal.
* @return The sound made by the animal, or "Unknown" if the animal is not recognized.
*/public String getAnimalSound(String animal) {
returnswitch (animal) {
casenull -> {
System.out.println("Oops! A null animal?");
yield"Unknown";
}
case String a when a.equalsIgnoreCase("Dog") -> "Bark";
case String a when a.equalsIgnoreCase("Cat") -> "Meow";
case String a when a.equalsIgnoreCase("Bird") -> "Tweet";
default -> "Unknown";
};
}
Assess Copilot's suggestion and, if you agree with the change:
In VS Code and Visual Studio: Click Accept.
In JetBrains: Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).
As with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.
If your coding standards require you to use the arrow notation for functions, and descriptive names for parameters, you can use Copilot to help you make these changes.
Put the cursor in the function name.
Open inline chat:
In VS Code: Press Command+i (Mac) or Ctrl+i (Windows/Linux).
In Visual Studio: Press Alt+/.
In JetBrains IDEs: Press Control+Shift+i (Mac) or Ctrl+Shift+g (Windows/Linux).
Type: use arrow notation and better parameter names and press Enter.
Support for this feature depends on having the appropriate language extension installed in your IDE for the language you are using. Not all language extensions support this feature.
Well chosen names can help to make code easier to maintain. Copilot in VS Code and Visual Studio can suggest alternative names for symbols such as variables or functions.
Put the cursor in the symbol name.
Press F2.
Visual Studio only: Press Ctrl+Space.
Copilot suggests alternative names.
Screenshot of a dropdown list in VS Code giving alternatives for a symbol name.
In the dropdown list, select one of the suggested names.