An over-length function---a signal to refactor

Source: Internet
Author: User

This, I often find to do the development of the colleague's code, this problem arises. "But the real key to making small functions easy to understand is a good name. If you can give a good name to a function, the reader can understand the function by name, without having to look at what is written in it. “
-----------a good name and see what the function does.   When necessary, for example, debugging, check the bug, this time, only need to view. "The end result is that you should be more aggressive in decomposing functions. We follow the principle that whenever we feel the need to annotate something with a note, we write what we need to say in a separate function and name it for its purpose, not the way it is implemented. We can do this for a group of even a short line of code. Even if the function call action is longer than the function itself, as long as the function name can explain its purpose, we should not hesitate to do so. The key is not the length of the function, but the semantic distance between what the function "does" and "How to do". "----------Write code according to this principle, decomposition function.  Also learned an advanced experience, the name of the function to explain the purpose of the function. "If you have a large number of parameters and temporary variables inside the function, they will hinder your function refinement." If you try to use the Extract method, you will eventually pass many parameters and temporary variables as parameters to the new function being refined, resulting in almost no improvement in readability. At this point, you can often use the replace temp with query technique to eliminate these temporary elements. Introduce Parameter object and preserve Whole object can make the long parameter columns more concise. "---------------------make the function argument list shorter------------------------------------------------------------------------------------ introduce Parameter object (introducing Parameter objects)
Usage Scenario: A set of parameters is always passed together as a parameter to several functions. This set of parameters is called the data clumps. You can then use this refactoring technique to shorten the list of parameters. Long parameter list, which causes the function to be difficult to understand.approximate steps to achieve:
1. Identify the above scenario, a set of parameters are always passed together as parameters of the function.
2. Create a new class with the name of the class that describes the meaning of the set of parameters. It is an immutable class.
The members are all final types, and the members are the parameters that are introduced.
3. Create a Get method for each member in the new class.
4. Gradually replace the function parameters with the members of the new class. 5. Then, check the action in the function, see what actions, can be refined into the parameter object, as a parameter corresponding behavior.
An operation that can be refined into a parameter object as the behavior of a Parameter object, a set of operations that has the following characteristics:
1). For this set of operations, the parameters used are all members of the Parameter object.
2). The purpose of this set of operations can be expressed by an action name. This action name is the name of the parameter object's behavior. examples of effects:
Getflowbetween (date start, date end)-------introduce Parameter object manipulation---->getflowbetween (Date range). Preserve Whole Object (keep objects intact)
the meaning of this manipulation:
int low = Daystemprange () *getlow ();
int high = Daystemprange () *gethigh ();
Withinplan = Plan.withinrange (low, high);
        |
| Apply Perserve Whole Object Technique
        |
Withinplan = Plan.withinrange (Daystemprange ()); Benefits of:
1. Suppose that, at some point, the required parameters of the function Withinrange are changed, for example, three parameters in an object need to be used instead of two parameters in an object. Then, if the refactoring was not previously used, then the called point of the function should be modified one by one.
2. Make the function's argument list shorter. Disadvantages:
"If you pass a numeric value, the called function relies only on these values, not on the objects they belong to." But if you pass an entire object, the object that the called function is on needs to depend on the parameter object. If this makes your dependency structure worse, then you should not use preserve Whole object technique. " other aspects of the understanding:
"If the called function uses many item data from another object, it may mean that the function should actually be defined in the object to which the data belongs. So, while considering preserve Whole object, you should also consider the move Method. ” implementation steps:
0. Identify which parameters belong to an object, or can be unified as a member of an object.
1. If the function parameter does not belong to an object, use the introduce Parameter object method to create a new object to contain the set of parameters. 2. Replace the reference to this parameter with the accessor that references the new object. Usually when done, it is found that the operation of the called function can be refined into the behavior of the Parameter object, which is a method of the Parameter object, a function.
Like what:
class Heatingplan:
boolean withinrange (Temprange roomrange) {return(Roomrange.getlow () >= _range.getlow () && Roomrange.gethigh () <= _range.gethigh ());}-------->--------------------- Make the function argument list shorter------------------------------------------------------------------------------------------------------ -Eliminate temporary variables within the function so that the function body gets shorter------------------------------------------------------- Replace temp with query (replaces temporary variable with query)  See a specific example: double GetPrice () {int baseprice = _quantity * _itemprice;     Double Discountfactor;     if (Baseprice > Discountfactor) = 0.95;     else Discountfactor = 0.98; return baseprice * discountfactor; }
Apply the Replace temp with query, which replaces the temporary variable with the query, to eliminate Baseprice, discountfactor the two temporary variables effect as follows: Double GetPrice () {return Baseprice () * Discountfactor ();} Implementation process: 1. Find temporary variables that are only assigned once. ---> If a temporary variable is assigned more than once, consider splitting it into multiple variables using split temporary variable. A temporary variable should assume only one responsibility, i.e. it should be assigned only once, except for the accumulator variable and the index variable. 2. Declare the temporary variable as final. 3. Compile. This ensures that the temporary variable is indeed assigned only once. 4. Extract the right part of the equal sign of the statement "Assign value to this temporary variable" to a separate function. ---> First declare the function as private. Later you may find that there are more classes that need to use it, and it is easy to relax and protect it. ---> Ensure that the extracted function has no side effects, meaning that the function does not modify any object content. If it has side effects, it is separatequery from the Modifler technique. A function, if it is a query, that is to return a value, or to modify the object's contents. You can't have two functions for a function, which makes the code difficult to read and error-prone. 5. Compile the test. 6. Use the inline temp method on the temporary variable. -------------------eliminate temporary variables within the function, which makes the function body shorter------------------------------------------------------- how do you determine which piece of code in the body of the refinement function? There are two kinds of signals: 1. Look for comments. If there is a line of comments in front of the code, you are reminded that you can replace the code with a function, and you can name the function on the basis of the comment. Even if there is only one line of code, if it needs to be commented out, it's worth refining it to a standalone function. 2. Conditional expressions and loops in function questions are also the extracted signals. To refine the loop into a separate function, this can make the original function body smaller. For the conditional expression in the function body, the decompose conditional technique is used to deal with it, and the purpose is to make the original function body smaller.

An over-length function---a signal to refactor

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.