How to implement code refactoring

Source: Internet
Author: User
Tags comments constant constructor error code inheritance split wrapper
Definition of refactoring

Refactoring is to improve its internal structure without changing the observable behavior of software. the rhythm of the reconstruction

Modify the program at a small pace. If you make a mistake, it's easy to find it. A method inside, should not have a lot of code, we can by decomposition after reorganization. Good code should clearly express its function, and variable name is the key to clear code. Minimize temporary variables, a large number of parameters are transmitted, it is easy to lose, poor readability. Extract the logical code for functional reuse.

Refactoring (noun): an adjustment to the internal structure of software to improve its understanding and reduce its modification cost without changing the observable behavior of software.
Refactoring (verb): Use a series of refactoring starters to adjust their structure without changing the observable behavior of the software. why refactoring. refactoring improved software design refactoring is software easier to understand refactoring to help find bug refactoring to improve programming speed when refactoring .

In almost any case I am opposed to a special pull-out time for refactoring. It seems to me that refactoring is not something that should be specifically allotted time to do, and refactoring should be done anywhere, anytime. You shouldn't refactor refactoring, you refactor because you want to do something else, and refactoring can help you get things done. three times Rule

Do something for the first time, just do it, the second time do something like that will be offensive, the third time to do something similar, you should refactor.
Charm, three reconstruction. Refactoring is useful for refactoring when refactoring a review code when reconstructing a patching error while adding functionality .

Difficult to modify a program difficult to read the logical repetition of adding a new behavior requires modifying the existing code with complex conditional logic

A good program is easy to read all logic is just to specify new changes in the unique location does not endanger existing behavior as simple as possible to express conditional logic

Refactoring is a process that takes place on a currently operational program without changing the behavior of the program, enabling us to continue to develop at a high speed, thus adding value to the program. When the should not be refactored. Unable to run the direct rewrite without refactoring the project and approaching deadlines, should not be refactored, although refactoring can improve productivity, but you don't have enough time, it's usually a sign that you should be refactoring sooner. bad taste of code Duplicated code repeat codes long method Large class long Parameter List over-length parameter column divergent change divergence shotgun surgery bulk bomb Modified Feature Envy attachment complex (strategy\visitor) data clumps Mud group Primitive obsession Basic type paranoid Switch statements switch thriller Show (use polymorphism substitution Parallel Inheritance hierarchies parallel inheritance system Lazy class redundant class speculative generality rhetoric futuristic temporary field confusing temporary field Message Chains Transition-coupled message chain middle man middleman inappropriate intimacy contempt relationship alternative Classes with Different Interfaces similar class incomplete Library class is not perfect libraries data class refused bequest rejected bequest Comments too many comments

When you feel the need to write comments, try refactoring first, and try to make all comments redundant. build a test system to ensure that all tests are fully automated so they can check their test results. A set of tests is a powerful bug scout that can significantly reduce the time it takes to find bugs. Run tests frequently. Every time you compile, take your tests into account-at least once every day for each test. Whenever you receive a bug report, please write a unit test to expose the bug. Writing imperfect tests and executing them is better than waiting for the perfect test. Consider the possible error boundary conditions and concentrate the test firepower there. When things are supposed to go wrong, don't forget to check if the expected exception was thrown. Do not write tests because the test cannot capture all bugs, because the tests can catch most bugs. Refactoring List

Refactoring the record format name description of the problem to be solved sketch diagrams show examples of pre-and post-refactoring example motivation practices

Basic techniques for refactoring-step forward, frequent testing

There is an innate relationship between patterns and refactoring. Patterns are the goals you want to reach, and refactoring is the way to get there.re-organize functionsExtract Method Refinement function you have a piece of code that can be organized together and come out independently. Put this code in a separate function and let the function name explain the purpose of the function. Inline method Inline function A function whose ontology should be as clearly understood as its name. Insert the function body at the function call point, and then remove the function. Inline temp Inline temporary variable you have a temporary variable that is assigned only once by a simple expression, and it interferes with other refactoring methods. Replace any reference action on the variable with the expression that assigns it. Replace temp with query has been queried to replace temporary variables your program saves the results of an expression with a temporary variable (temp). The expression is refined into a standalone function (query-queried). Replace all referenced points of this temporary variable with a call to the new function. The new function can be used by other functions. Introduce explaining Variable introduction of explanatory variables you have a complex expression. Put the result of this complex expression (or part of it) in a temporary variable that explains the purpose of the expression with this variable name. Split temporary Variable decomposition TEMP variable Your program has a temporary variable assigned more than once, which is neither a loop variable nor a set with a temporary variable (collecting temporary Variable). For each assignment, create an independent. The corresponding temporary variable. Remove Assignments to Parameters remove the assignment of a parameter your code assigns an action to a parameter. Replace the position of the parameter with a temporary variable. Replace method with method object replaces a function with a function object you have a large function where the use of local variables makes it impossible for you to adopt the Extract method. Put this function in a separate object so that the local variable becomes the domain within the object, and then you can decompose the large function into several small functions in the same object. Substitute algorithm replacement algorithm you want to replace an algorithm with another one that is clearer. Replace the function body with another algorithm.Move attributes between objectsMove method Shift function in your program, there is a function that has more communication with the other class than the class in which it is stationed: Call the latter, or be called by the latter. Create a new function with similar behavior in the class that is most commonly referenced by the function. Turn the old function into a simple delegate function or completely remove the old function. Extract class Refinement in your program, a field (value range) is used more by another class outside the class. Create a new field at Target class, modify all users of the source field, and make them use new field instead. The Inline class classes the class to do something that should be done by two. Create a new class that moves the relevant range and function from the class to the new class. Hide Delegate hides the Delegate class of the delegate class client directly calling its server object (the service object). Create all the functions required by the customer at the sever end (a class) to hide the delegate relationship. Remove middle man removes the middleman a class makes too many simple delegates (simply delegation). Let the customer call delegate directly (the Trustee Class). Introduce Foreign method introduces an additional function the server class you are using requires an extra function, but you cannot modify the class. Create a function in the client class and use a server class entity as the first argument (argument). Introduce local Extension introduce native extensions the server class you use requires some extra functions, but you can't modify this class. Create a new class so that it contains these extra functions. Let this extension be the subclass (subclass) or (wrapper) outer covering of the source class.Reorganize DataSelf encapsulate field from encapsulated fields you directly access a range (field), but the direct coupling to the range becomes unwieldy. The value/SetPoint function is established for this range, and only these functions are available to access the domain. Replace data value with object to replace values with objects you have a data item that requires additional data and behavior. Turn this data item into an object. Change value to Reference object to reference object you have a class that derives many equality views (equal instance), and you want to replace them with cell objects. Turn this value object (the real value) into a reference object. Change Reference to value converts a reference object to a Value object (equals Hashcode) you have a Reference object, which is small, immutable, and difficult to manage. Turn him into a value object (a real value).

Replace array with object replaces arrays with objects you have an array of elements that each represent different things, replacing an array with an object. For each element in the array, it is represented by a range of domains.

Duplicate observed data copy "Monitored" You have some domain data in the GUI control, and the domain method needs to be accessed. That is, the data is copied to the domain object. Create a observer mode that synchronizes control (sync) of duplicate data within domain object and GUI object.

Change Unidirectional Association to bidirectional changing one-way association to two-way Association two classes all need to use each other's attributes, but only one one-way connection in between. Adds a reverse pointer and enables the modification function to update both connections at the same time.

Change Bidirectional Association to unidirectional changes the bidirectional association to one-way correlation two classes have two-way associations, but one class now no longer requires another class feature. Remove unnecessary associations (association).

Replace magic number with symbolic Constant replaces magic numbers with literal constants you have a literal value with a special meaning. Create a constant, name it according to its meaning, and replace the literal value above with the constant.

Encapsulate field Package fields there is a public domain for your class. Declare it as private and provide the appropriate access function.

The encapsulate Collection Package collection has a function that returns a cluster (Collection). This function returns a read-only image of the cluster and provides a function to add the removed cluster elements in this class.

Replace record with data class replaces records in a structure you need to face the record structure in a traditional programming environment. Create a dummy data object for the record (recording) (Dumb.

Replace type code with class replaces the type code with a value code class, but does not affect class behavior. Replace the numeric type code with a new class. Replace type code with subclasses substituting a subclass code (polymorphic mechanism) you have an immutable type code that affects the behavior of class. Replace this type code with a subclass. Replace type code with State/strategy to State/strategy instead of code you have a type code that affects the behavior of class, but you can't use subclassing. Replace type code with state object. Replace subclass with Field replaces subclasses with fields the only difference between your individual subclasses is only the function that returns the constant data. Modify these functions so that they return to a (new) value in superclass and then destroy the sublcasses.

Simplified conditional expression Decompose Conditional decomposition conditional expression you have a complex conditional statement. Separate functions are proposed from the if, then, and else three paragraphs respectively. Consolidate Conditional expression Combining conditional expressions you have a series of conditional tests that get the same results. Combine these tests into a single conditional and refine the conditional into a single function. Consolidate Duplicate Conditional Fragments Merge duplicate conditional fragments with the same code on each branch of the conditional. Move the repeating code beyond the criteria. The Remove control flag removal controls flag (Break/continue/return) in a series of Boolean expressions, a variable has the effect of a control tag, replacing the control mark with a break statement or a return statement. Replace Nested Conditional with guard clauses the use of a Guardian statement instead of a nested conditional expression (independently judging the conditional logic in the function called the "guardian statement") makes it difficult to see the normal execution path. Use the Guardian statement to represent all special situations. Wei statement is the complex conditional expression is split into multiple conditional expressions, such as a very complex expression, nested several layers of if-then-else statements, converted to multiple if statements, the implementation of its logic, the multiple if statement is the Guardian statement Replace Conditional With polymorphism replacing conditional expressions with multiple states you have a conditional on your hand that chooses different behavior depending on the type of object. Place each branch of the conditional into an overwrite function within a subclass, and then declare the original function as an abstract function. Introduce null object introduces null objects you need to check for a null value repeatedly. Replace null value (invalid value) with null object (invalid) Introduce assertion introduces the assertion that a piece of code needs to make some assumptions about the state of the program. Express this hypothesis with assertion (assertion).simplifying function calls The name of the function renamed by the Rename method function failed to reveal the purpose of the function and modify the function name. Add Parameter adding parameters a function needs to get more information from the caller. Add an object parameter to the function to bring the object into the required information for the function. Remove Parameter Removing the parameter function body no longer requires a parameter to remove the parameter. Separate query from Modifier the Function object state value is returned and the state of the object is modified by separating a function from the queried function and modifying the function. In the future two different functions, one of which is responsible for querying, the other is responsible for modification. Parameterize method allows functions to carry a number of functions to do similar work, but it contains different values in the function body. Create a single function that expresses those different values with parameters. Replace Parameter with Explicit Methods replace the parameter with a definite function you have a function that takes a different reaction depending entirely on the parameter values. For each possible value of this parameter, create a separate function. Preserve Whole object to keep objects intact you take a value out of an object and use it as a parameter to a function call. The reference (passed) the entire object. Replace Parameter with Methods invokes a function with a function instead of a parameter object and passes the resulting result as an argument to another function. The function that accepts the parameter can also call the previous function. Let the parameter recipient remove the key parameter and call the previous function directly. Introduce Parameter object introduces parameter objects a parameter always appears naturally at the same time. Replace these parameters with an object. Remove Setting Method Removes a set function a value in your class should be set at the start of the object and then no longer changed. Remove all the setup functions for that range. The Hide method hidden function has a function that has never been used by any other class. Change this function to private. Replace Constructor with Factory method replaces a constructor with a factory function you want to create an object not just to do simple construction work, but to replace the CONSTRUCOTR (constructor) with Factory Method (Factory function) Encapsulate the downcast wrapper down transforms the object returned by a function that needs to be performed by the function caller to perform a downward transition action. Moves the down transition action to the function. Replace Error CodE with Exception replace the error code with an exception a function returns a specific code that represents some kind of error condition. Use exceptions instead. Replace Exception with test replaces the exception in the face of a condition that a caller can check beforehand, you throw an exception. Modify the caller so that it checks before calling the function. working with generalized relationships The Pull up field field moves up two subclass with the same range. Move this range to superclass. The pull up Method function moves up some functions, producing exactly the same effect in each subclass. Move the function to superclass. Pull up Constructor body constructor body Move up you have some constructors in each of your subclass, and their ontologies are almost identical. Create a new constructor in superclass and call it in the subclass constructor. The push down Method function moves down a function in superclass only with partial, not all, subclass. Move this function to the relevant subclasses. The Push down field field moves down one of the value domains in superclass only partially subclass. Take this range to the subclasses that need it. Some of the attributes in the Extract subclass refinement subclass class are only used by some rather than all entities. Create a new subclass and move the part of the feature described above to subclass. Extract Superclass refined two classes have similar characteristics. Build a superclass for this classes. Move the same attribute to superclass. Extract Interface Refining interface Several customers use the same subset in the class interface. Alternatively, the two classes interfaces are partially the same. The same subset is refined into a separate interface. Collapse Hierarchy Folding Inheritance system superclass and subclass are not much different. and make them as one. The Form template method shapes The templating function with some subclasses, where some of the corresponding functions perform similar actions in the same order, but the measures are actually different. Each measure is put into a separate function, and the same signature is maintained, so the original function becomes the same. Then move the original function up to superclass. Replace inheritance with delegation takes a delegate instead of inheriting a subclass that uses only part of the superclass interface, or more data that does not need to be inherited. Create a new value in subclass to save the superclass, adjust the subclass function, make it change and delegate superclass, and then remove theThe inheritance relationship between the two. Replace delegation with inheritance uses a delegate relationship between the two classes with inheritance instead of the delegate, and often writes many extremely simple vivisystems functions for the entire interface. Let Vivisystems class inherit the Trustee class.Large-scale refactoringTease Apart inheritance to comb and decompose the inheritance system and assume two responsibilities at the same time. Build two inheritance systems and let one of them call another by delegating relationships. Convert procedural design to Objects converting a process to object design you have some code on your hands, written in a traditional, procedural style. The data record becomes an object, separates the behavior, and moves the behavior into the related object. Separate domain from Presentation the domain login (domain logic) is included in some GUI classes that separates the field from presentation/display. Separate domain loginc (domain logic) and create separate domain classes for them. Extract Hierarchy Refining Inheritance System you have a class that does too much work, and one part of the work is done in a lot of terms. Establish an inheritance system to represent a special case with a subclass.

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.