Sometimes you want to extract a single line of code or a portion of a line of code as its own method. For example, you might have a calculation that is done as part of a line of code but is common enough to warrant its own method. Alternatively, you might need to extract an object assignment to add additional logic to it. In either case, the code editor supports this type of extraction.
Let’s look at an example. Suppose you have the following line of code that calculates an invoice’s total inside a loop through the invoice items list.
total += item.Price * item.Quantity;
You might want to extract just the portion of the assignment that calculates a line item’s total (price * quantity). To do so, you select the portion of code and invoke the Extract Method refactor using the Quick Actions (light bulb) via Ctrl+. or from the context menu. Figure 9.17 shows this operation in action for the selected code.
Notice that, by default, the new method would like an instance of InvoiceLineItem
. You might prefer to pass both quantity and unit price instead. You would have to make these changes manually. Alternatively, if quantity and unit price were assigned to variables before the extraction was done, you would get a new method that accepted these parameters (instead of an InvoiceLineItem
instance). Figure 9.18 demonstrates this fact.
The resulting refactor replaces a portion of the line of code with the following.
total = total + GetItemTotal(price, quantity);
It also adds the new method, as follows.
private static double GetItemTotal(double price, short quantity) {
return price * quantity;
}