Reconstruction Method 08: replace method with method object (replace function with function object)

Source: Internet
Author: User

 

You have a large function where the use of local variables makes it impossible to use the extract method (extraction function ).Put this large function into a single 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: the presence of local variables increases the difficulty of function decomposition. If local variables in a function are flooded, it is very difficult to break down the function. Replace temp with query (replacing temporary variables with queries) can help relieve this burden, but sometimes you will find that you cannot disassemble a function at all. In this case, function objects should be used.

Practice: 1. Create a new class and name it based on the purpose of the function to be processed.

2Create a const field in the new class to save the object where the original large function is located. We call this field "source object ". At the same time, for each temporary variable and each parameter of the original function, create a corresponding field in the new class to save it.

3Create a constructor in the new class to receive all parameters of the source object and the original function.

4Create a compute () function in the new class.

5, Convert the original function'sCodeCopy to the compute () function. To call any function of the source object, use the source object field.

6, Compile.

7Replace the function ontology of the old function with the statement "Create a new object of the new class and then call the compute () function ".

Because all local variables are now fields, you can break down this large function without passing any parameters.

 

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.