How-To's

Generalizing the algorithm

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:
Refactoring

Technorati tags: extract method, push members down, refactoring, ReSharper, .NET
image description