Reconstruction Techniques: reorganizing functions [5]. Restructuring manipulation functions

Source: Internet
Author: User

Reconstruction Techniques: reorganizing functions [5]. Restructuring manipulation functions

Total returned directory

Directory of this section

  • Replace Method with Method Object (Replace functions with function objects)
  • Substitute Algorithm (replacement Algorithm)

  • Stage Summary
8 Replace Method with Method Object (Replace functions with function objects) Summary

You have a large function where the use of local variables makes it impossible to use the Extract Method.

Put this function into a separate object, so that local variables become fields in the object. Then you can break down this large function into multiple small functions in the same object.

Motivation

We have been emphasizing that small functions are beautiful and moving. As long as the relatively independent code is extracted from a large function, the readability of the function is greatly improved.

However, the existence of local variables increases the difficulty of function decomposition. If a function is flooded with local variables, Replace Temp with Query can help you at this time. Sometimes a function to be disassembled cannot be disassembled at all, so Replace Method with Method Object plays a role.

Replace Method with Method Object converts all local variables into the fields of the function Object. Then we can use the Extract Method to create a new function for this new function, so as to achieve the purpose of dismantling.

Example

If you want to find a suitable example, it will take a long time, so we have fabricated such a function.

class Account{      int Gamma(int inputVal, int quantity, int yearToDate)      {           int importantValue1 = inputVal * quantity + Delta();           int importantValue2 = inputVal * yearToDate + 100;           if (yearToDate - importantValue1 > 100)           {               importantValue2 -= 20;           }           int importantValue3 = importantValue2 * 7;           //and so on...           return importantValue3 - 2 * importantValue1;       }       public int Delta()       {           return 100;       }}

To turn this function into a function object, first declare a new class. In the new class, a field is provided to save the original object, and each parameter and each temporary variable of the function are also provided to save the field.

class Gamma{        private readonly Account _account;        private readonly int _inputVal;        private readonly int _quantity;        private readonly int _yearToDate;        private int _importantValue1;        private int _importantValue2;        private int _importantValue3;}

Next, add a constructor:

public Gamma(Account account, int inputVal, int quantity, int yearToDate){       _account = account;       _inputVal = inputVal;       _quantity = quantity;       _yearToDate = yearToDate;}

Next, move the original function to Compute.

public int Compute(){    _importantValue1 = _inputVal * _quantity + _account.Delta();    _importantValue2 = _inputVal * _yearToDate + 100;    if (_yearToDate - _importantValue1 > 100)    {       _importantValue2 -= 20;    }    _importantValue3 = _importantValue2 * 7;    //and so on...    return _importantValue3 - 2 * _importantValue1;}

The complete Gamma function is as follows:

class Gamma{   private readonly Account _account;   private readonly int _inputVal;   private readonly int _quantity;   private readonly int _yearToDate;   private int _importantValue1;   private int _importantValue2;   private int _importantValue3;
public Gamma(Account account, int inputVal, int quantity, int yearToDate) { _account = account; _inputVal = inputVal; _quantity = quantity; _yearToDate = yearToDate; } public int Compute() { _importantValue1 = _inputVal * _quantity + _account.Delta(); _importantValue2 = _inputVal * _yearToDate + 100; if (_yearToDate - _importantValue1 > 100) { _importantValue2 -= 20; } _importantValue3 = _importantValue2 * 7; //and so on... return _importantValue3 - 2 * _importantValue1; }}

Finally, modify the old function to delegate its work to the newly completed function object.

int Gamma(int inputVal, int quantity, int yearToDate){    return new Gamma(this, inputVal, quantity, yearToDate).Compute();}

This is the basic principle of this reconstruction. It has the following advantages: now we can easily take the Extract Method for the Compute () function without worrying about parameter passing.

For example, we refactor Compute as follows:

public int Compute(){    _importantValue1 = _inputVal * _quantity + _account.Delta();    _importantValue2 = _inputVal * _yearToDate + 100;    GetImportantThing();    _importantValue3 = _importantValue2 * 7;    //and so on...    return _importantValue3 - 2 * _importantValue1;}void GetImportantThing(){    if (_yearToDate - _importantValue1 > 100)    {        _importantValue2 -= 20;    }}
Summary

This refactoring method is intended for large functions, and there are many local variables in it, so this refactoring method may make you suddenly understand.

9 Substitute Algorithm (replacement Algorithm) Overview

You want to replace an algorithm with another clearer algorithm.

Replace the function Ontology with another algorithm.

Motivation

I am sure you have done this question since you were a child: Please use more than two solutions to answer this question. This means that there must be more than one solution to a question, and some methods will certainly be simpler than others. The same is true for algorithms.

If you find that there is a clearer way to do one thing, you should replace the more complex way in a clearer way. With a deeper understanding of the problem, you will often find that there are simpler solutions beyond the original practice. At this time, you have to change the original algorithm.

Example

Let's take a simple function as an example:

string FoundPerson(string[] people){    foreach (var person in people)    {        if (person == "Don")        {            return "Don";        }        if (person == "John")        {            return "John";        }        if (person == "Kent")        {            return "Kent";        }    }    return string.Empty;}

By analyzing this algorithm, we find that if a list set is used, the function is simpler and clearer. Therefore, after reconstruction, the Code is as follows:

string FoundPerson(string[] people){    var candidates = new List<string>() { "Don", "John", "Kent" };    foreach (var person in people)    {        if (candidates.Contains(person))        {            return person;        }    }    return string.Empty;}
Summary

Before using This refactoring method, make sure that you have decomposed the original function as much as possible. It is very difficult to replace a huge and complex algorithm. Only by dividing it into simple small functions can you confidently Replace the algorithm.

Stage Summary

The title of these sections is "re-organizing functions". As the name suggests, these refactoring methods are all for functions to better wrap the code. In almost all moments, the problem stems from the Long Method (too Long function), the bad taste of the Code ).

An important refactoring Method for long functions is the Extract Method, which extracts a piece of code from the original function and puts it into an independent function. Inline Method is the opposite. It replaces a function call with the function ontology.

The biggest difficulty in refining a function is to process local variables, one of which is temporary variables. When processing a function, you can use Replace Temp with Query to remove all possible temporary variables. If a Temporary Variable is used in multiple places, use Split Temporary Variable to make it easier to replace.

If the temporary variables are too messy, it is difficult to replace them. At this time, Replace Method with Method Object should be launched.

The parameters are slightly less problematic, provided that you do not assign them to the functions. If you do this, use Remove Assignments to Parameters.

After the function is decomposed, I can know how to make it work better. Some algorithms can be improved to make the code clearer. This requires Substitute Algorithm to introduce clearer algorithms.

 

To Be Continued...

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.