Boost Your Refactoring Efficiency with VS Code: Extract Method Shortcut

Hady MuhammedHady Muhammed
2 min read

As software engineers, we constantly strive for cleaner, more maintainable code. One powerful technique to achieve this is refactoring, and among the various refactoring techniques, Extract Method stands out for its ability to simplify complex functions by breaking them into smaller, more manageable pieces.

In this article, I'll introduce you to a handy shortcut in Visual Studio Code (VS Code) that makes the Extract Method refactoring a breeze. This little trick can significantly speed up your workflow and improve code quality.

What is Extract Method?

Extract Method is a refactoring technique where you move a block of code into a new method (or function) and then replace the original code with a call to the new method. This can help:

  • Reduce code duplication

  • Improve readability

  • Simplify debugging and testing

The Shortcut

To use the Extract Method shortcut in VS Code, follow these steps:

  • Set up the shortcut in the vscode settings: Go to Preferences Ctrl + P and then write and choose Preferences: Open Keyboard Shortcuts (JSON) as shown below

Add the keyboard shortcut: copy this object to the settings keybindings.json file to enable the refactoring menu , then save the file.

Example

Let's say we have the following JavaScript function:

If you noticed that the function needs to be refactored its more than 30 lines and the rule is if the function exceeds 10 lines .. its probably doing more than one thing.

We can simplify this by extracting the else logic into a separate method using the Keyboard shortcut:

Click on "Extract to method in class" from the sub-menu.

Name the New Method: Let's call it getProfile.

Conclusion

Refactoring is a critical skill for any software engineer, and tools like VS Code make it easier and more efficient. By leveraging the Extract Method shortcut, you can keep your code clean, maintainable, and scalable.

Give it a try in your next coding session, and you'll see how this small trick can make a big difference in your development workflow!

0
Subscribe to my newsletter

Read articles from Hady Muhammed directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Hady Muhammed
Hady Muhammed