17.3. Refactoring Actions
The following sections describe each of the refactoring options and provide examples of how to use built-in support for both C# and Refactor! for VB.NET.
17.3.1. Extract Method
One of the easiest ways to refactor a long method is to break it up into several smaller methods. The Extract Method refactoring action is invoked by selecting the region of code you want moved out of the original method and selecting Extract Method from the context menu. In C#, this will prompt you to enter a new method name, as shown in Figure 17-10. If there are variables within the block of code to be extracted that were used earlier in the original method, they will automatically appear as variables in the method signature. Once the name has been confirmed, the new method will be created immediately after the original method. A call to the new method will replace the extracted code block.
Figure 17.10. Figure 17-10
For example, in the following code snippet, if you wanted to extract the conditional logic into a separate method, then you would select the code, shown with a gray background, and choose Extract Method from the right-click context menu:
private void button1_Click(object sender, EventArgs e) { string output = Properties.Settings.Default.AdventureWorksCS; if (output == null) { output = "DefaultConnectionString"; } MessageBox.Show(output); /* ... Much longer method ...