Reconstruction Method 45: Separate Query Form modifier (separate the query function from the modification function)

Source: Internet
Author: User

A function returns the object status value and modifies the object status.Create two different functions, one for query and the other for modification.

Motivation: If a function only provides you with a value without any side effects, it is very valuable. You can call this function at will, or move the call Action to another part of the function. It is a good idea to clearly show the difference between the two functions "with side effects" and "without side effects. No function with returned values should have any side effects. SomeProgramMembers even use this as a required rule.

If you encounter a function that has both returned values and side effects, you should try to split the query action from the modification action.

There is a common optimization method: cache the query results in a field, so that subsequent repeated queries can greatly speed up. Although this method changes the object state, this modification is imperceptible, because you always get the same results regardless of any query.

Practice: 1. Create a New query and make it return the same value as the original function.

2Modify the original function to call the query function and return the obtained result.

3, Compilation, and testing.

4, Will call the original functionCodeCall the query function, and add the call to the original function before calling the query function. Compile and test each modification.

5Change the return value of the original function to void, and delete all return statements.

 

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.