How to Refactor Code in Visual Studio Code

Michiel Mulders
Michiel Mulders
6
May
2021
|
6 min read
This article looks at how you can refactor your code using Visual Studio Code (VS Code) and Visual Studio Code plugins.

In this article, we'll explore how you can refactor your code using the Visual Studio Code (VS Code) code editor. We’ll also explore the best VS Code extensions.

Refactoring improves code’s internal structure without altering the current behaviour. 

Refactoring your code helps your team manage technical risk. The act of refactoring improves code quality and maintainability. This, in turn, removes the risk of accumulating technical debt when building features. It also aids in writing tests. Refactoring can help you identify and address technical issues quickly and effectively. 

It's a good practice for development teams to plan a refactoring week to evaluate the code architecture and internal structure before starting a new development cycle. 

You’ll learn: 

  • How to refactor your code using Visual Studio Code 
  • The best refactoring plugins and tools for VS Code
  • Why you should refactor code

1. Refactoring with Visual Studio Code Shortcuts

First, let’s look at VS Code’s native shortcuts to do some basic code refactoring. We’ve created a small source code example using JavaScript to help you play around with these functionalities.

Here’s an index.js file that contains business logic. We import a `userModule`, retrieve a new user object, and convert the user’s name to uppercase.

Refactoring in VSCode

Next, here’s the implementation of the `userModule`, which contains several exported functions that we use in our `index.js` file. The file is nested in two folders. The resulting path is `/modules/users/retrieve.js`.

Visual Studio extensions for refactoring example

If we right-click on the `getUser` function in the `index.js` file, we’ll see different options to help us with refactoring the code. Here are three of the most useful options:

  • Go to definition: Opens up a pane that shows you where the function has been defined
  • Go to implementation: Brings you to the function definition in the `modules/users/retrieve.js` file
  • Find all references: Shows you all locations where a function has been used, and it shows you every function usage within a file

The above commands are most useful for quickly navigating and finding function definitions in Visual Studio Code. For instance, you want to figure out in which files a particular function has been used. Therefore, you can use the above commands to solve such tasks quickly.

2. Automatically Fix Imports and Filenames

When refactoring code, web developers often can't resist criticising poorly chosen filenames. On top of that, refactoring code means shifting code between different files and changing the purpose of certain modules. As a result, broken imports can be a common issue when refactoring is complete. 

Thankfully, Visual Studio Code can help save developers from having to scan through all files to find broken imports manually. When a filename is changed in Visual Studio Code, the user will be asked if they'd like to update imports automatically. To do so, select the "Always automatically update imports" option. This can be tested by renaming the `retrieve.js` file from the previous example.

Fixing imports in VSCode

Now, create a new folder and move the `retrieve.js` file to this folder. When doing so, VS Code will show you another pop-up message asking if you want to update imports when moving files automatically. Again, select the “Always automatically update imports” option. That’s it!

3. Built-in Code Formatting by Visual Studio Code

From the VS Code documentation, we can read how the built-in formatting option works.

> VS Code has default formatters for JavaScript, TypeScript, JSON, and HTML. Each language has specific formatting options (for example, `html.format.indentInnerHtml`), which you can tune to your preference in your user or workspace settings. 

To trigger the formatting option, you can open the Command Palette (use the keyboard shortcut shift + CMD + P) and look for the option “Format Document”. Select this option to format your document. Most likely, this won’t change much to your code except for fixing some indentation issues.

If you want Visual Studio Code to automatically trigger the “Format Document” option whenever you make changes to a file, you can configure this via the user settings. We prefer to format the document whenever hitting the save button (CMD + S). To do so, open your user settings and look for the rule `editor.formatOnSave`. Click the checkbox next to the rule to enable it.

Code formatting in VSCode

Alternatively, you can choose `editor.formatOnType`, which formats a line after typing, or `editor.formatOnPaste`, which formats content when you paste it in your editor.

When choosing a formatting rule, you don’t need to do anything else to enable this rule.

4. Use Extensions That Make Refactoring Easy

We can install extensions to make our lives much easier when using VS Code. Some of these tools should be considered standard practices which are used consistently in modern engineering teams.

1) Stepsize

Stepsize is a must-have tool for modern engineering teams to track refactoring work, collaborate on refactoring manage sprints from within VS Code.

The Stepsize tool brings all the features of Jira right into VS Code. This makes it much easier to report and resolve code that needs refactoring and get it prioritised. 

With Stepsize, you can

  • Create and resolve issues, such as refactoring work, directly from VS Code
  • Link your issues to code to see issues affecting the features you’re working on
  • Add refactoring work to your sprints with our Jira integration
  • Visualise areas that might need refactoring in your codebase with an in-editor visualisation
VS Code extensions - Stepsize

Stepsize enables teams to decide what to refactor and report issues seamlessly from within VS Code. But it does so much more. Ultimately, Stepsize enables elite engineering teams to radically improve quality, efficiency and predictability.

It’s easy to get started. Install the VSCode extension or the Jetbrains extension here

2) Prettier ESLint

We don’t need to use the built-in code formatting tool provided by VS Code. We can disable the default language formatter and replace it with a custom language formatter or one provided by an extension like Prettier.

We have to open the user settings again to enable the Prettier formatter as our default formatter for all languages. Look for the following rule `editor.DefaultFormatter` and pick the Prettier formatter called `esbenp.prettier-vscode`.

Prettier ESLint for VSCode

We need to add Prettier configuration rules to tell Visual Studio Code how to format our document. The easiest way is by creating a `.prettierrc`configuration file in the project's root. This file will contain a JSON object which holds all the active rules. The advantage of this approach is that you can commit the configuration file to your repository to enforce the same coding standards across your team. This standardisation will reduce refactoring work in the future.

Here are some popular rules that can help you to refactor code quickly:

  • tabWidth: Specify the number of spaces per indentation level
  • semi: Print semicolons at the ends of statements
  • singleQuote: Use single quotes instead of double quotes
  • arrowParens: Include parentheses around a sole arrow function parameter, which we want to avoid in this example

3) JavaScript Booster

JavaScript Booster is a code refactoring tool that features several coding actions such as converting var to const or let, removing redundant else statements, and merging declaration and initialisation. Just note the light bulb at the left and press it to learn how to transform the code under the cursor.

JS Booster

4) SonarLint

SonarLint lets you fix coding issues before they exist: like a spell checker, SonarLint highlights Bugs and Security Vulnerabilities as you write code, with clear remediation guidance so you can fix them before the code is even committed. SonarLint in VS Code supports analysis of JavaScript, TypeScript, Python, Java, HTML & PHP code.

SonarLint VSCODE

Rounding up

Refactoring code and tracking your refactoring work is an essential practice for any developer. Not only does it tackle technical debt and reduce technical risks, but it also helps to keep your codebase organised and maintainable. Refactoring code should be part of any development team’s regular workflow. 

Refactoring in VSCode can be made much easier when we know how to get the most out of this powerful software. When it comes to refactoring tools and plugins, you have many options to choose from.

Choose linting tools that make sense for your codebase, and use them consistently in your workflow. Use linters alongside Stepsize to ensure your team is tracking code that needs refactoring and building it into your sprints.

You can install Stepsize’s VSCode extension or the Jetbrains extension here

DATE:  
DURATION:  
 minutes
No items found.
No items found.