Generalizing the algorithm
August 14th, 2006 by ObfuscatorOne of the common tasks developers face on a regular basis is generalizing an algorithm. This How-To describes how a combination of ‘Extract Method’ and ‘Push Members Down’ refactorings can help you streamline this task.
Suppose that you have some code for calculating yearly bonuses for your customers:

Now you want to award bonus points differently for private and corporate customers. ReSharper to the rescue!
- Extract Method from
o.BillingAmount / 100: select it, then press Ctrl + Alt + M (alternatively, you can go to the ‘Refactor This’ menu by pressing Ctrl + Shift + R and then select ‘Extract Method’:

In the Extract Method dialog, provide the name of the new method and make sure to make it non-static and not private:

After you click Continue, the code looks like the following:

- Push Members Down on
GetBonusForOrder():

In the Push Members Down dialog, check the method and make sure to select its ‘Make Abstract’ checkbox:

After you click Continue, the code looks like the following:

So, you’ve got an abstractGetBonusForOrderinCustomerclass and two overrides inCorporateCustomerandPrivateCustomer(which are identical as yet). Modify their implementations as necessary, and voila!
Read more about the features discussed in this How-To:
Refactoring
Tags: ReSharper

August 15th, 2006 at 7:10 pm
How would you refactor if you wanted the Bonus calculation to be a method on the order? I always wind up doing this mostly by hand.
August 16th, 2006 at 11:43 am
Brien,
You can do that in two steps:
1. Invoke Make Method Static on GetBonusForOrder
You will get:
int GetBonusForOrder(Customer c, Order o)
2. Invoke Make Method Non-Static and select parameter ‘o’ as future this. You will get (in Order class)
int GetBonusForOrder(Customer c)
You can get rid of parameter ‘c’ if it is not needed via Change Method Signature refactoring.
Bear in mind though, that in case of virtual methods this trick obviuosly won’t work.
I think we can post a separate article on this refactoring combination.