PHP code refactoring makes your code more efficient. Reorganize your function

Source: Internet
Author: User
I will write down my favorite and interesting topics and share them with you. The last time I wrote an article "talking with the boss in php". I still have a lot of questions. This book helps me introduce a lot. 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. for 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 Method1 and short functions: it takes some effort to read the code, because we must change the context frequently 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.


"Functions" are 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. several attribute variables in Large Class1 and 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 Statements1 and 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. 5. Introduce Explaining Variable puts the results of complex expressions (or some of them) into a temporary Variable and uses the Variable name to explain the purpose of the expression.

Motivation: The expression is complex and hard 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. Create 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, replace it with a temporary variable.


VII. Replace Method with Method Object

The use of local variables by large functions cannot use the Extract Method. Put this Method into a separate object, so that the local variable becomes the filed of the object, 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 the 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.

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.