Extract method refactoring

Split and Organize code into DRY, discrete units.

Tip Screenshot

Code must be refactored for readability and maintenance. Of the many refactorings a developer might use, the Extract Method refactoring enables us to write and organize code better.

When to extract a method

When functions become too large, they become harder to read and maintain. So we need to split them out into smaller functions, and organize the code to call those smaller functions when needed.

Sometimes, we see code that's been copied and pasted that can be consolidated into a single function. Or perhaps the code wasn't copied and pasted, but it's still not DRY (Don't Repeat Yourself), because two or more blocks of code produce the same output or behavior. That kind of code should also be refactored into a single function.

Lastly, some programmers use a "stream of consciousness" workflow in which they get code working first, then to return and immediately refactor it into something more efficient and maintainable.

These are some scenarios where the Extract Method refactoring can make development more smooth.

How to use Extract Method refactoring

In Rider, highlight the code you want to extract and press ⌘⇧R (macOS) / Ctrl+Shift+R (VS Windows/Linux). Choose the type of method you want: method or local function. Supply the name, return type, parameters, visibility, and location and other information requested in the refactoring dialog. This information is used to create a new method or local function for the selected code to live in, as well as calls to it.


Related Resources

Use collection initializers
Update and initialize items in old collection declarations
Rename refactoring
Would a variable by any other name read as clearly?
Inline method refactoring
Replace usages of a function with its implementation.