Generalizing the algorithm

Mikhail Kropotov

One 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:
We want to generalize the behavior of the Customer class
Now you want to award bonus points differently for private and corporate customers. ReSharper to the rescue!

  1. 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’:
    Use the Extract Method refactoring
    In the Extract Method dialog, provide the name of the new method and make sure to make it non-static and not private:
    Extract Method dialog
    After you click Continue, the code looks like the following:
    Method is extracted
  2. Push Members Down on GetBonusForOrder():
    Now use the Push Members Down refactoring
    In the Push Members Down dialog, check the method and make sure to select its ‘Make Abstract’ checkbox:
    Push Members Down dialog
    After you click Continue, the code looks like the following:
    Now you have one abstract method and two overrides.
    So, you’ve got an abstract GetBonusForOrder in Customer class and two overrides in CorporateCustomer and PrivateCustomer (which are identical as yet). Modify their implementations as necessary, and voila!

Read more about the features discussed in this How-To:

Comments below can no longer be edited.

2 Responses to Generalizing the algorithm

  1. Brien says:

    August 15, 2006

    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.

  2. dsl says:

    August 16, 2006

    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.


Subscribe to .NET Tools updates