{"meta":{"title":"Refactoring code with GitHub Copilot","intro":"Leverage Copilot artificial intelligence to help you refactor your code quickly and effectively.","product":"GitHub Copilot","breadcrumbs":[{"href":"/en/copilot","title":"GitHub Copilot"},{"href":"/en/copilot/tutorials","title":"Tutorials"},{"href":"/en/copilot/tutorials/refactor-code","title":"Refactor code"}],"documentType":"article"},"body":"# Refactoring code with GitHub Copilot\n\nLeverage Copilot artificial intelligence to help you refactor your code quickly and effectively.\n\n## Introduction\n\nRefactoring 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.\n\nThis article gives you some ideas for using Copilot to refactor code in your IDE.\n\n> \\[!NOTE] Example responses are included in this article. GitHub Copilot Chat may give you different responses from the ones shown here.\n\n## Understanding code\n\nBefore you modify existing code you should make sure you understand its purpose and how it currently works. Copilot can help you with this.\n\n1. Select the relevant code in your IDE's editor.\n2. Open inline chat:\n\n   * **In VS Code:** Press <kbd>Command</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>i</kbd> (Windows/Linux).\n   * **In Visual Studio:** Press <kbd>Alt</kbd>+<kbd>/</kbd>.\n   * **In JetBrains IDEs:** Press <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>g</kbd> (Windows/Linux).\n3. In the input box for inline chat, type a forward slash (`/`).\n4. In the dropdown list, select **/explain** and press <kbd>Enter</kbd>.\n5. If the explanation that Copilot returns is more than a few lines, click **View in Chat** to allow you to read the explanation more easily.\n\n## Optimizing inefficient code\n\nCopilot can help you to optimize code - for example, to make the code run more quickly.\n\n### Example code\n\nIn the two sections below, we'll use the following example bash script to demonstrate how to optimize inefficient code:\n\n```bash\n#!/bin/bash\n\n# Find all .txt files and count lines in each\nfor file in $(find . -type f -name \"*.txt\"); do\n    wc -l \"$file\"\ndone\n```\n\n### Use the Copilot Chat panel\n\nCopilot can tell you whether code, like the example bash script, can be optimized.\n\n1. Select either the `for` loop or the entire contents of the file.\n\n2. Open Copilot Chat by clicking the chat icon in the activity bar or by using the keyboard shortcut:\n\n   * **VS Code and Visual Studio:** <kbd>Control</kbd>+<kbd>Command</kbd>+<kbd>i</kbd> (Mac) / <kbd>Ctrl</kbd>+<kbd>Alt</kbd>+<kbd>i</kbd> (Windows/Linux)\n   * **JetBrains:** <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>c</kbd>\n\n3. In the input box at the bottom of the chat panel, type: `Can this script be improved?`\n\n   Copilot replies with a suggestion that will make the code more efficient.\n\n4. To apply the suggested change:\n\n   * **In VS Code and JetBrains:** Hover over the suggestion in the chat panel and click the **Insert At Cursor** icon.\n\n     ![Screenshot of the 'Insert at cursor' icon in the Copilot Chat panel.](/assets/images/help/copilot/insert-at-cursor.png)\n\n   * **In Visual Studio:** Click **Preview** then, in the comparison view, click **Accept**.\n\n### Use Copilot inline chat\n\nAlternatively, if you already know that existing code, like the example bash script, is inefficient:\n\n1. Select either the `for` loop or the entire contents of the file.\n\n2. Open inline chat:\n\n   * **In VS Code:** Press <kbd>Command</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>i</kbd> (Windows/Linux).\n   * **In Visual Studio:** Press <kbd>Alt</kbd>+<kbd>/</kbd>.\n   * **In JetBrains IDEs:** Press <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>g</kbd> (Windows/Linux).\n\n3. Type `optimize` and press <kbd>Enter</kbd>.\n\n   Copilot suggests revised code. For example:\n\n   ```bash\n   find . -type f -name \"*.txt\" -exec wc -l {} +\n   ```\n\n   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.\n\n4. Assess Copilot's suggestion and, if you agree with the change:\n\n   * **In VS Code and Visual Studio:** Click **Accept**.\n   * **In JetBrains:** Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).\n\nAs with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.\n\n## Cleaning up repeated code\n\nAvoiding 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.\n\nIn the following very simple JavaScript example, the same calculation (item price multiplied by number of items sold) is performed in two places.\n\n```javascript\nlet totalSales = 0;\n\nlet applePrice = 3;\nlet applesSold = 100;\ntotalSales += applePrice * applesSold;\n\nlet orangePrice = 5;\nlet orangesSold = 50;\ntotalSales += orangePrice * orangesSold;\n\nconsole.log(`Total: ${totalSales}`);\n```\n\nYou can ask Copilot to move the repeated calculation into a function.\n\n1. Select the entire contents of the file.\n\n2. Open inline chat:\n\n   * **In VS Code:** Press <kbd>Command</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>i</kbd> (Windows/Linux).\n   * **In Visual Studio:** Press <kbd>Alt</kbd>+<kbd>/</kbd>.\n   * **In JetBrains IDEs:** Press <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>g</kbd> (Windows/Linux).\n\n3. Type: `move repeated calculations into functions` and press <kbd>Enter</kbd>.\n\n   Copilot suggests revised code. For example:\n\n   ```javascript\n   function calculateSales(price, quantity) {\n     return price * quantity;\n   }\n\n   let totalSales = 0;\n\n   let applePrice = 3;\n   let applesSold = 100;\n   totalSales += calculateSales(applePrice, applesSold);\n\n   let orangePrice = 5;\n   let orangesSold = 50;\n   totalSales += calculateSales(orangePrice, orangesSold);\n\n   console.log(`Total: ${totalSales}`);\n   ```\n\n4. Assess Copilot's suggestion and, if you agree with the change:\n\n   * **In VS Code and Visual Studio:** Click **Accept**.\n   * **In JetBrains:** Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).\n\nAs with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.\n\n## Making code more concise\n\nIf code is unnecessarily verbose it can be difficult to read and maintain. Copilot can suggest a more concise version of selected code.\n\nIn the following example, this Python code outputs the area of a rectangle and a circle, but could be written more concisely:\n\n```python\ndef calculate_area_of_rectangle(length, width):\n    area = length * width\n    return area\n\ndef calculate_area_of_circle(radius):\n    import math\n    area = math.pi * (radius ** 2)\n    return area\n\nlength_of_rectangle = 10\nwidth_of_rectangle = 5\narea_of_rectangle = calculate_area_of_rectangle(length_of_rectangle, width_of_rectangle)\nprint(f\"Area of rectangle: {area_of_rectangle}\")\n\nradius_of_circle = 7\narea_of_circle = calculate_area_of_circle(radius_of_circle)\nprint(f\"Area of circle: {area_of_circle}\")\n```\n\n1. Select the entire contents of the file.\n\n2. Open inline chat:\n\n   * **In VS Code:** Press <kbd>Command</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>i</kbd> (Windows/Linux).\n   * **In Visual Studio:** Press <kbd>Alt</kbd>+<kbd>/</kbd>.\n   * **In JetBrains IDEs:** Press <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>g</kbd> (Windows/Linux).\n\n3. Type: `make this more concise` and press <kbd>Enter</kbd>.\n\n   Copilot suggests revised code. For example:\n\n   ```python\n   import math\n\n   def calculate_area_of_rectangle(length, width):\n     return length * width\n\n   def calculate_area_of_circle(radius):\n     return math.pi * (radius ** 2)\n\n   print(f\"Area of rectangle: {calculate_area_of_rectangle(10, 5)}\")\n   print(f\"Area of circle: {calculate_area_of_circle(7)}\")\n   ```\n\n4. Assess Copilot's suggestion and, if you agree with the change:\n\n   * **In VS Code and Visual Studio:** Click **Accept**.\n   * **In JetBrains:** Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).\n\nAs with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.\n\n## Splitting up complex units of code\n\nLarge 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.\n\nCopilot can help you to split up complex blocks of code into smaller units that are more suitable for reuse.\n\nThe 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.\n\n```python\nimport pandas as pd\nfrom pandas.io.formats.style import Styler\n\ndef process_data(item, price):\n    # Cleanse data\n    item = item.strip()  # Strip whitespace from item\n    price = price.strip()  # Strip whitespace from price\n    price = float(price) # Convert price to a float\n    # More cleansing operations here\n\n    # Create and print a DataFrame\n    data = {'Item': [item], 'Price': [price]}\n    df = pd.DataFrame(data)\n    print(df.to_string(index=False))\n\n# Example usage\nitem = \"   Apple \"\nprice = \" 1.25\"\nprocess_data(item, price)\n```\n\nTo split up the `process_data` function:\n\n1. Put the cursor in the function name.\n\n2. Open inline chat:\n\n   * **In VS Code:** Press <kbd>Command</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>i</kbd> (Windows/Linux).\n   * **In Visual Studio:** Press <kbd>Alt</kbd>+<kbd>/</kbd>.\n   * **In JetBrains IDEs:** Press <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>g</kbd> (Windows/Linux).\n\n3. Type: `split into 2 separate functions: one for cleansing data, the other for printing` and press <kbd>Enter</kbd>.\n\n   Copilot suggests revised code. For example:\n\n   ```python\n   def cleanse_data(item, price):\n     # Cleanse data\n     item = item.strip()  # Strip whitespace from item\n     price = price.strip()  # Strip whitespace from price\n     price = float(price)  # Convert price to a float\n     return item, price\n\n   def print_data(item, price):\n     # Create and print a DataFrame\n     data = {'Item': [item], 'Price': [price]}\n     df = pd.DataFrame(data)\n     print(df.to_string(index=False))\n\n   def process_data(item, price):\n     item, price = cleanse_data(item, price)\n     print_data(item, price)\n   ```\n\n   > \\[!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.\n\n4. Assess Copilot's suggestion and, if you agree with the change:\n\n   * **In VS Code and Visual Studio:** Click **Accept**.\n   * **In JetBrains:** Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).\n\nAs with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.\n\n## Rewrite conditional code for better readability\n\nThere 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.\n\nThis Java method uses a series of `if` and `else if` statements to determine which operation to perform:\n\n```java\npublic String getSound(String animal) {\n  if (animal == null) {\n      System.out.println(\"Oops! A null animal?\");\n  } else if (animal.equalsIgnoreCase(\"Dog\")) {\n      return \"Bark\";\n  } else if ( animal.equalsIgnoreCase(\"Cat\")) {\n      return \"Meow\";\n  } else if ( animal.equalsIgnoreCase(\"Bird\")) {\n      return \"Tweet\";\n  }\n  return \"Unknown\";\n}\n```\n\nA `switch` statement might be a better way of applying the same logic.\n\n1. Put the cursor in the method name.\n\n2. Open inline chat:\n\n   * **In VS Code:** Press <kbd>Command</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>i</kbd> (Windows/Linux).\n   * **In Visual Studio:** Press <kbd>Alt</kbd>+<kbd>/</kbd>.\n   * **In JetBrains IDEs:** Press <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>g</kbd> (Windows/Linux).\n\n3. 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`.\n\n   This demonstrates how you can use a single prompt to ask Copilot to make multiple changes.\n\n4. Press <kbd>Enter</kbd>.\n\n   Copilot suggests revised code. For example:\n\n   ```java\n   /**\n    * Retrieves the sound made by a given animal.\n    *\n    * @param animal The name of the animal.\n    * @return The sound made by the animal, or \"Unknown\" if the animal is not recognized.\n    */\n   public String getAnimalSound(String animal) {\n       return switch (animal) {\n           case null -> {\n               System.out.println(\"Oops! A null animal?\");\n               yield \"Unknown\";\n           }\n           case String a when a.equalsIgnoreCase(\"Dog\") -> \"Bark\";\n           case String a when a.equalsIgnoreCase(\"Cat\") -> \"Meow\";\n           case String a when a.equalsIgnoreCase(\"Bird\") -> \"Tweet\";\n           default -> \"Unknown\";\n       };\n   }\n   ```\n\n5. Assess Copilot's suggestion and, if you agree with the change:\n\n   * **In VS Code and Visual Studio:** Click **Accept**.\n   * **In JetBrains:** Click the Preview icon (double arrows), then click the Apply All Diffs icon (double angle brackets).\n\nAs with all Copilot suggestions, you should always check that the revised code runs without errors and produces the correct result.\n\n## Reformat code to use a different structure\n\nSuppose you have this function in JavaScript:\n\n```javascript\nfunction listRepos(o, p) {\n return fetch(`https://api.github.com/orgs/${o}/repos?per_page=${parseInt(p)}`)\n   .then((response) => response.json())\n   .then( (data) => data);\n}\n```\n\nIf 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.\n\n1. Put the cursor in the function name.\n2. Open inline chat:\n\n   * **In VS Code:** Press <kbd>Command</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>i</kbd> (Windows/Linux).\n   * **In Visual Studio:** Press <kbd>Alt</kbd>+<kbd>/</kbd>.\n   * **In JetBrains IDEs:** Press <kbd>Control</kbd>+<kbd>Shift</kbd>+<kbd>i</kbd> (Mac) or <kbd>Ctrl</kbd>+<kbd>Shift</kbd>+<kbd>g</kbd> (Windows/Linux).\n3. Type: `use arrow notation and better parameter names` and press <kbd>Enter</kbd>.\n\n   Copilot suggests revised code. For example:\n\n   ```javascript\n   const listRepos = (org, perPage) => {\n     return fetch(`https://api.github.com/orgs/${org}/repos?per_page=${parseInt(perPage)}`)\n       .then(response => response.json())\n       .then(data => data);\n   };\n   ```\n\n## Improving the name of a symbol\n\n> \\[!NOTE]\n>\n> * VS Code and Visual Studio only.\n> * 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.\n\nWell 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.\n\n1. Put the cursor in the symbol name.\n\n2. Press <kbd>F2</kbd>.\n\n3. **Visual Studio only:** Press <kbd>Ctrl</kbd>+<kbd>Space</kbd>.\n\n   Copilot suggests alternative names.\n\n   ![Screenshot of a dropdown list in VS Code giving alternatives for a symbol name.](/assets/images/help/copilot/rename-symbol.png)\n\n4. In the dropdown list, select one of the suggested names.\n\n   The name is changed throughout the project."}