Improved code design-Composing Methods)

Source: Internet
Author: User

1. Extract Method (extraction function)
Explanation: if the code of a function is found to be very long, it is very likely that the function has done a lot of things. check whether there are comments in the function, comments are usually used to explain what the following code does. You can consider refining this code into an independent function.

The advantage of doing so is self-evident. It is the Single Responsibility Principle in the five basic principles of object-oriented. Long functions are split into small functions, which will facilitate code reuse.

Before impulse: 00 public void Print (Employee employee)

01 {

02 // print employees information

03 Console. WriteLine ("Name:" + employee. Name );

04 Console. WriteLine ("Sex:" + employee. Sex );

05 Console. WriteLine ("Age:" + employee. Age );

06

07 // print employees salary

08 Console. WriteLine ("Salary:" + employee. Salary );

09 Console. WriteLine ("Bonus:" + employee. Bonus );

10}
Impulsive: 00 public void Print (Employee employee)

01 {

02 // print employees information

03 PrintInfo (employee );

04

05 // print employees salary

06 PrintSalary (employee );

07}

08

09 public void PrintInfo (Employee employee)

10 {

11 Console. WriteLine ("Name:" + employee. Name );

12 Console. WriteLine ("Sex:" + employee. Sex );

13 Console. WriteLine ("Age:" + employee. Age );

14}

15 public void PrintSalary (Employee employee)

16 {

17 Console. WriteLine ("Salary:" + employee. Salary );

18 Console. WriteLine ("Bonus:" + employee. Bonus );

19}

2. Inline Method (Inline Function)
Explanation: some functions are very short, have only one or two lines, and the code intent is very obvious. In this case, you can consider killing this function and directly using the code in the function.

Too many methods in the object will make people feel uncomfortable. After removing unnecessary functions, the code will be more concise.

Before impulse: 0 public bool IsDeserving (int score)

1 {

2 return IsScoreMoreThanSixty (score );

3}

4

5 public bool IsScoreMoreThanSixty (int score)

6 {

7 return (score> 60 );

8}
Impulsive: 0 public bool IsDeserving (int score)

1 {

2 return (score> 60 );

3}

3. Inline Temp (Inline temporary variables)
Explanation: if a temporary variable (Temp) is used to indicate the return value of a function, this is a good practice. however, if this temporary variable is really redundant, it will not affect the code reading after it is inline, or even this temporary variable hinders other refactoring work, it should be internalized.

The advantage of killing this temporary variable is that it reduces the length of the function and sometimes makes other refactoring work smoother.

Before impulse: 0 int salary = employee. Salary;

1 return (salary> 10000 );
Impulsive: 0 return (employee. Salary> 10000 );

4. Replace Temp With Query (use the Query method to Replace the temporary variable)
Explanation: The program has a temporary variable (Temp) used to save the computation result of an expression. This computation expression is extracted (Extract) into an independent function (I .e., a Query type, replace all calls to this temporary variable with calls to the new function (Query). The new function can also be used by other functions.

The advantage is to reduce the function length and increase the code reuse rate, which facilitates further code reconstruction. note that Replace Temp With Query is often an essential step before the Extract Method, because local variables make the Code not easy to Extract, therefore, you can replace them with the query type before performing similar refactoring.

The following example shows how to Replace Temp With Query. imagine that totalPrice was used in many code blocks in the function before the impulse. suddenly one day I found this function was too long and I needed to extract the code from this block into a separate function, in this way, you need to put totalPrice = price * num; into every extracted function. if the query type is used in the original function, this problem does not exist. if the Query formula has a large amount of computing, we do not recommend using Replace Temp With Query.

Before impulse: 0 public double FinalPrice (double price, int num)

1 {

2 double totalPrice = price * num;

3 if (totalPrice> 100)

4 return totalPrice * 0.8;

5 else

6 return totalPrice * 0.9;

7}
Impulsive: 00 public double FinalPrice (double price, int num)

01 {

02 if (TotalPrice (price, num)> 100)

03 return TotalPrice (price, num) * 0.8;

04 else

05 return TotalPrice (price, num) * 0.9;

06}

07 public double TotalPrice (double price, int num)

08 {

09 return price * num;

10}

5. Introduce Explaining Variable (Introduce understandable variables)
Explanation: many conditions in conditional logical expressions are difficult to understand. Why do we need to satisfy these conditions? Unclear. You can use Introduce Explaining Variable to extract each Condition Clause and use an appropriate temporary Variable name to indicate the meaning of the Condition Clause.

The advantage is that it increases the readability of the program.

Before impulse: 0 if (operateSystem. Contains ("Windows "))&&

1 (browser. Contatins ("IE ")))

2 {

3 // do something

4}
After Impulse: 0 bool isWindowsOS = operateSystem. Contains ("Windows ");

1 bool isIEBrowser = browser. Contatins ("IE ");

2 if (isWindowsOS & isIEBrowser)

3 {

4 // do something

5}

6. Split Temporary Variable (clear Temporary variables)
Explanation: for example, there is a temporary variable in the code that represents the rectangular perimeter somewhere in the function and is assigned an area under the function, that is, the temporary variable is assigned more than once, and not the same amount. assign an independent temporary variable for each assignment.

A variable must represent only one amount. Otherwise, the code reader may be confused.

Before impulse: 0 double temp = (width + height) * 2;

1 // do something

2 temp = width * height;

3 // do something
After Impulse: 0 double perimeter = (width + height) * 2;

1 // do something

2 double area = width * height;

3 // do something

7. Remove Assignments to Parameters (Remove the parameter assignment Operation)
Explanation: There are two types of input parameters: "pass value" and "transfer address". If it is "transfer address", it is understandable to change the parameter value in the function, because we want to change the original value. however, if it is "pass value", assigning values to parameters in the code will be confusing. therefore, a temporary variable should be used in the function to replace this parameter, and other values should be assigned to this temporary variable.

Before impulse: 0 public double FinalPrice (double price, int num)

1 {

2 price = price * num;

3 // other calculation with price

4 return price;

5}
Impulsive: 0 public double FinalPrice (double price, int num)

1 {

2 double finalPrice = price * num;

3 // other calcu

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.