PHP: refactoring-improving the design of existing code: reorganizing your function and restructuring to improve the design of existing code

Source: Internet
Author: User

[Switch] PHP comments "refactoring-improving the design of existing code": reorganizing your function and improving the design of existing code.
Original article address: re-organize your function Mind Map and click "refactoring-improving the design of existing code" in PHP to view the big picture.

Introduction: I will write down my favorite and important topics and share them with you. The last time I wrote an article "talking with the boss in php". I still have many questions. This book has helped me a lot. If you are too busy or too reluctant to read the text, it is recommended that you directly read the text. You can use the code in the comparison to understand the advantages and disadvantages. Why do I use graphs in the Code section? Because I often use my cell phone to read the code, the code of the blog garden is messy on the mobile phone, and it is quite comfortable to see the figure. After all, we use English letters to encode professional terms. Therefore, we can use some English words to better demonstrate our professionalism. If you have mastered the following English words, you will be more direct and professional when communicating with other coder. -- Let's see it. "*" Indicates the inline: inline function: function * method: method finely grained: fine-grained rename: rename query: query temp: temporary (temporary) -- usually refers to the Temporary variable * extract: extract -- I personally prefer to translate it into "extract" * duplicate: Copy split: Anatomy variable: variable factor: factor, factor reconstruction principle 1. What is reconstruction? Noun form: an adjustment to the internal structure of the software. The purpose is to improve the comprehensibility of the software without changing its observability and reduce its modification costs. Verb form: uses a series of refactoring rules to adjust the structure of software without changing the behavior that can be observed. Ii. Why rebuild? 1. Regular refactoring allows the code to maintain this pattern. 2. Let the code find a proper position. 3. Make the software easier to understand. 4. You can find bugs. 5. Increase our encoding speed.

Iii. refactoring challenges 1. Modifying the interface name if the method in your class is public, you may be at great risk during rename, you don't know which modules are calling your method (we often do grep operations in the entire project, and then look at the calls and logic of each module one by one ). -- Therefore, when writing classes, whether it is the attribute or method, we try to achieve private as much as possible to avoid opening interfaces. 2. When should we rebuild? (1) rewrite all the code. The existing code is too messy. refactoring is better than rewriting. (2) reconstruction should be avoided when the project is nearing completion. We can put the reconstruction to the second phase to solve the problem.

 

Bad taste of Code 1. Duplicate Code 1. The same class. The two methods contain the same expression. Solution: You can use the Extract Method to Extract duplicate code, and then let both methods call this Extract Method. 2. Two classes have similar methods. Solution: (1) propose two classes to construct a parent class. (2) Delete the method of one class and call the method of another class. Ii. Long Method 1. Short functions: it takes some effort to read the code, because we must often convert the context to see what the subroutine has done. But the key to making small method easy to understand is a good name. Readers can understand the functions by name, so they don't have to look at what they write. -- In earlier programming languages, calling methods requires additional overhead, which makes coder unwilling to use small method. However, modern OO languages have almost no additional overhead (function calls) in process ). 2. annotate the local refining signal: whenever we feel that we need to annotate something, we will write the things to be explained into an independent function and name it for its purpose. You can do this for a group or even just one line of code. -- As long as the function name can explain its users, we should not hesitate to do so. "Function" is understood as "what to do" or "How to do" 3. conditional and loop are often refining signals. 4. An example of code cleansing. Let's think about it!

3. Large Class 1. Several attribute variables in the Class have the same prefix or suffix and can use Extract Class. 2. Not most variables in the Class use attribute variables, and Extract Class can be used. 3. There is too much code to Extract Class. 4. Long Parameter is used as the Introduce Parameter Object. -- I don't agree with this because when I use others' methods, I seldom look at code practices, let alone those attributes or methods of objects used in them, the data I want is retrieved. 5. Switch Statements 1. Use less switch Statements. -- The problem lies in duplication. When adding a new case, you must locate all the cases and modify them. 2. Replace it with polymorphism. Practice: 1. Execute the switch Extract Method; 2. MoveMethod put the practice Code in case into the multi-variant class. 6. Try using Extract Method for Comments. If not, try Rename Method. When you feel that you need to write comments, try refactoring first and try to make all comments redundant. Annotations are generally used for future plans and for areas you are not sure about (why do you do something ).
Reorganizing your function Long Method often contains too much information, which is covered up by complicated logic and difficult to identify. I. Extract Method condition: If I see a function that is too long or requires a comment to make people understand the purpose of the code, I will put this code into an independent function, and let the function name explain the purpose of the function.

 

Motivation:

Short and well-named function: -- finely grained

1. Large opportunities for reuse.

2. The function reads a series of comments.

3. Function overwriting is easy.

Key: the Key to function length lies in the semantic distance between function names and function bodies. If the extraction action can enhance the Definition of the code, do it.

Practice:

1. Create a new function, and name it based on the function's intent-name it "what it is", rather than "how it is.

= "Even if the Extract Function is very simple, for example, it is just a message or Function call, as long as the new Function can demonstrate the code intent in a better way, you should also refine it. But if you can't think of a more meaningful name, don't touch it.

2. Move the Extract code from the Source Function to the New Function.

Ii. Inline Method

When the Method Body is as clear and easy to understand as the Method Name, please use the Inline Method.

 

3. Inline Temp

A temporary variable is assigned only once by a simple expression and only once after being assigned. -- Please Inline Temp

 

Iv. Replace Temp with Query

If a Temp variable saves an expression, the expression Extract Method is used. -- This is the so-called query type.

 

Motivation:

1. Local variables make the code hard to be extracted.

2. Temporary variables will drive you to write longer code. If you change it to query method, you can obtain this information for the method in the class. -- Write a clearer code.

3. Replace Temp with Query is often an essential step before you use the Extract Method.

Practice:

1. Find the temporary variable assigned only once.

=> If a Temporary Variable is assigned more than once, use Split Temporary Variable to Split it into multiple variables.

2. the right part of the value assignment to Temp Variable is Extract into an independent function.

=> Declare the Method as private. If other classes are used in the future, release it (public or protected ).

  

If the code is well organized, you can often find more effective optimization solutions. ---- If the performance is really bad, it is easy to put it back. V. Introduce Explaining Variable Put the results in a complex expression (or part of it) into a temporary variable, and use this variable name to explain the purpose of the expression. 

  Motivation:Expressions are complex and difficult to read. In this case, temporary variables can help you break down expressions into easy-to-manage forms. 6. Split Temporator Variable a temporary Variable is assigned more than once. It is neither a cyclic Variable nor a collection Variable. So Creates an independent temporary variable for each assignment.

 

 

Motivation:

1. If a temporary variable bears multiple responsibilities, it should be replaced with multiple temporary variables. Each variable takes only one responsibility.

2. The same temporary variable handles two different things, which will confuse the review.

6. Remove Assignments To Parameters if your Code assigns a value To the parameter The position where this parameter is replaced by a temporary variable..

 

VII. Replace Method with Method Object

The use of local variables by large functions cannot use the Extract Method. SoPut this Method into a separate object, so that the local variable becomes the object's filed, and then the large function is decomposed into several small methods in the same object.

 

 

Motivation:

1. Extract relatively independent code from a large Method to greatly improve code readability.

2. In a Method, local variables are flooded and it is very difficult to break down this function.

3. Replace Method with Method Object converts all local variables into the value range of the Object. Then perform the Extract Method on the new object.

8. Substitute Algorithm if you want to replace an Algorithm with another clearer Algorithm Replace Method Body with another algorithm. -- Directly modify the original Method Body. Motivation: with more understanding of the problem, you can find a clearer way to replace the complicated method with a clearer way. Summary: this is only part of this book. I know that many coder may have different ideas. I also agree with them, and some do not agree with them. Therefore, we need to "change from good to bad ". You are welcome to express your views.

 

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.