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

This entry was posted in How-To's and tagged . Bookmark the permalink.

2 Responses to Generalizing the algorithm

  1. Brien says:

    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:

    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.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>