Rebuild Reading Notes and Eclipse rebuild functions, and rebuild eclipse
Chapter 2 reconstruction principles
What is refactoring?
Reconstruction (TERM): an adjustment to the internal structure of the software. The purpose is to improve the comprehensibility of the software without changing the [suspicious behavior of the software] and reduce the modification cost.
Refactoring (verb): uses a series of refactoring principles (techniques) to adjust the structure without changing the [suspicious behavior of software.
Two hats: New features and refactoring cannot be added at the same time.
Why rebuild?
Improved Software Design: it may be the best design in the world at the beginning based on existing needs. However, many functions may be added or deleted during the process. The original design does not meet the existing requirements.
Make the software easier to understand:
Generally, adding more comments is not necessarily a good choice, because the code may be modified by others, and the modified comments are ignored. Reading comments in the future has become a hindrance to understanding.
Programs are written to people, not to computers.
Locate the BUG: the refactoring process needs to be sorted out to identify multiple features, or to iterate and couple the bugs together.
Programming speed improvement: easy to understand, itself is to improve the development speed of new features.
When to refactor?
When adding features, modifying errors, reviewing code,
Reconstruction difficulties?
Database, modification interface,
When Will reconstruction not be changed?
The logic of the Code is chaotic, and nothing can be added at all. In some cases, it may need to be completely rewritten. However, we recommend that you split the code into multiple small modules and then gradually refactor and recreate it.
The project is nearing the deadline.
First design and then develop, but there is no need to worry about the most flexible design solutions. You only need to select the most reasonable solution, implement it, and then continuously try, verify, feedback, and modify it in practice.
Because it is never possible to predict subsequent changes in the early stage, and it is impossible to consider all the details during design, and it is not necessary.
Refactoring and performance?
Three methods
Time pre-algorithm (evaluate the execution time and execution chain of each task)
Continuous attention (note in the process, but sometimes it will lead to slow development or hard to understand the Program)
Post-Development (focus on high performance consumption)
The origin of refactoring?
1980 Smalltalk
Chapter 3 bad taste of code
3.1 Duplicated Code (repeated Code)
Repeated Logic Functions (in the same class, multiple subclasses, and different classes)
3.2 Long Method (Long function)
A function has only one function. In this case, there are few more than 15 rows.
The more features in the method, the more difficult it is to reuse. Or redundant Reuse
3.3 Large Class (too Large Class)
3.4 Long Parameter List (too Long Parameter column)
Or too many global variables can be divided into new classes.
3.5 Divergent Change (Divergent Change)
In the original class, too many functions are required.
3.6 Shotgun Surgery (elastic bullet modification)
The development of a function involves many changes. Why don't I put a class function into a class?
3.7 Feature Envy (Attachment)
Put things that are always changing together. Data and the behavior of referencing such data are always changing.
3.8 Data Clumps (Data dashboard)
A class contains too much or too little data and is distributed across multiple classes.
3.9 Primitive Obsession (basic type paranoid)
Reluctant to put a type of data source into a new data class
3.10 Switch Statements)
Replace with polymorphism?
3.11 Paralle lInheritance Hierarchies (parallel inheritance system)
All functions of sub-classes are extracted to the parent class. Or simply create a class to create an object reference.
3.12 Lazy Class (redundant Class)
The function itself is very complicated. After reconstruction, there are too few functions or few calls, so we can simply delete this class.
3.13 Speculative Generality (exaggerated)
It is designed to facilitate expansion in the future, but it may be used only for a long time.
3.16 Middle Man (Man in the Middle)
Half of A class's functions are delegated to other classes.
3.14 Temporary Field (confusing Temporary Field)
Scattered Data is extracted into a new data class.
3.15 Message Chains (over-coupled Message Chains)
For A function of object A, call B-> C-> D-> F-> E. Finally, E only has the desired function. Can we extract all the processes together? A directly calls the extracted object. (Public object)
3.17 Inappropriate Intimacy (relationship)
The parent class and the Child class are over-called, or the two classes can be seen as too many calls to each other. They simply put the over-called methods together.
3.18 Alternative Classeswith Different Interfaces (similar class)
Class or function
3.19 Incomplete Library Class (imperfect Library Class)
Add extension for Class Library
3.20 Data Class (pure Data Class)
3.21 Refused Bequest (rejected gifts)
Some classes do not need the function of their parent classes.
3.22 Comments (too many Comments)
Chapter 6 reorganizing functions
6.1 Extract Method (extraction function)
Motivation:
The function has a smaller granularity and a greater chance of reuse.
High-level functions read like a series of comments
Function rewriting is easier.
Practice:
Eclipse selects several lines of code, selects Refactory-> Extract Method, or uses the shortcut key (Alt + Shift + M)
Select any code, convert it to a function, and add the return type of the parameter automatically.
6.2 Inline Method (Inline Function)
Motivation: Sometimes you may find it easier to directly use the code in a function than to extract the code as a function.
Practice:
Select the function name in Eclipse, select Refactory-> Inline, or use the shortcut key Alt + Shift + I
Replace the place where this function is called with the content of this function. Select any function to use this function. (There are two options: All invocations and Only the selected invocation)
6.3 InlineTemp (Inline temporary variable)
Motivation: some temporary variables may be thought-provoking.
Directly change to the use of variables, and delete temporary variables
6.4 ReplaceTempwithQuery (replace temporary variables with queries)
Motivation: hinders extraction functions and puts computation into fixed functions.
6.5 IntroduceExplainingVariable (Introducing explanatory variables)
Select the expression in Eclipse, select Refactory-> Extract Local Variable, or use the shortcut key Alt + Shift + L
It is usually used as an expression to extract one of the local variables. For example, 3 + 5 is extracted as int I = 3;
6.6 SplitTemporaryVariable (break down temporary variables)
Motivation: a temporary variable is assigned only once. If assigned multiple times, it assumes more than one responsibility. This will easily confuse readers.
6.7 RemoveAssignmentstoParameters (remove the value assigned to the parameter)
Pass-by-value)
Http://www.blogjava.net/heis/archive/2009/04/23/267256.html
Pass-by-refrence)
6.8 ReplaceMethodwithMethodObject (replace the function with a function object)
If a function contains a large number of temporary variables and cannot be split into fine-grained functions, you can put the function into a new class, so that the temporary variables in the function become global variables in this class, fine-grained functions can be extracted at will.
6.9 SubstituteAlgorithm (replacement algorithm)
Chapter 7 moving between objects
In the process of Object design, it is very important to decide where to place the responsibilities. It is usually annoying, but Refactoring can change your original design.
7.1 Move Method (shift function)
Motivation: there are too many coupling actions between the two classes, so that the two classes can be cleaned up by moving the function.
Practice:
Set the function to be moved to static. In this way, we can see that all the global variables and methods of the current class are referenced in this method, and these parameters are replaced with the function parameters.
Then, use Eclipse to select the function name, select Refactory-> Move, or use the shortcut key (Alt + Shift + V) to Move the field to another class, and Move the class to another package.
7.2 Move Field (Move Field)
Motivation: as the system develops, you will find that you need a new classes and need to drag the original work responsibilities to the new class.
Practice: Use Eclipse to select a field, select Refactory-> Move, or use the shortcut key (Alt + Shift + V) to Move the field to another class, and Move the class to another package.
7.3 Extract Class (refining Class)
Motivation: A lot of data is scattered everywhere. Logically, data that can be divided can be put into one class.
Practice: Use Eclipse to select a field and select Refactory-> Extract Class
When all the selected fields are mentioned in the new class, you can choose to create a file or make the internal class
7.4 Inline Class (link the Class)
Motivation: there are not many behaviors in the class, which is opposite to Extract class.
7.5 Hide Delegate (Hide "delegation relationship ")
Motivation: reduce coupling between classes through "delegation relationship.
7.6 Remove MiddleMan (Remove man in the middle)
Opposite to 7.5
7.7 Introduce Foreign Method (introduces an additional function)
Motivation: all parameters of a function use the value of the same data object. The data object is directly transferred into the function.
7.8 Introduce Local Extension (introducing Local extensions)
Motivation: new support needs to be added when Source Code cannot be directly modified.
Practice: Inherit and add the function.
Chapter 8 reorganizing data
8.1 Self Encapsulate Field (Self-encapsulated value range)
Motivation: whether to directly use a field or add setter/getter is always controversial. We recommend that you use a field directly. This mode will automatically change when setter/getter is required.
Practice:
The Eclipse refactoring tool can automatically perform such operations.
Select attributes in Eclipse and select Refactor-> Encapsulate Filed.
1. Set the getter/setter name
2. How to modify this field? use setter and getter (Replace the reference with the set and get methods, and keep the original field reference mode unchanged in keep field refrence)-> OK
3. Insert new method after
8.2 Replace Data Value with Object (Replace Data Value with Object)
Motivation: at the initial stage of development, you may only need simple data items. As more and more pipe data items are developed, you can change the data value to an object.
Practice:
The Eclipse refactoring tool can automatically perform such operations.
Eclipse selects Refactor-> Extract Class in the Class to Extract fields.
1. Class name specifies the new data name
2. Destination: whether to create a new class file or use the internal class form
3. Select fields for extracted class. You can check the extracted fields and Edit the type and field name on the right side of the Select fields for extracted class.
4. Field name specifies the Field name of the new data object used in the current class.
8.3 Change Value to Reference (Change Value to Reference object)
Motivation:
Practice:
8.4 Change Reference to Value (Change the referenced object to a Value object)
8.5 Replace Array with Object (Replace Array with Object)
Motivation:
Practice:
String [] person = new String [3];
Person [0] = "18 ";
Person [1] = "name ";
Modified Effect
8.6 DuplicateObservedData (copy "monitored data ")
The values displayed in multiple parts of the GUI are associated or identical (place the data in one place)
8.7 changeunidirectionalassociationtobidireal Al (change one-way Association to two-way Association)
A References B and wants to modify it to A references B. B also references
8.8 ChangeBidirectionalAssociationtoUnidirectional (Change bidirectional Association to unidirectional Association)
Opposite to 8.7
8.9 ReplaceMagicNumberwithSymbolicConstant (replace the magic number with a literal constant)
Motivation: the magic number is used directly. The problem is that others do not know what the magic number means. Why must it be a number? The same logic may be used in multiple places, modifications made in only one place will not be forgotten in other places.
Practice:
The Eclipse refactoring tool can automatically perform such operations.
In Eclipse, select the magic number to be extracted as a constant. Here is the selected number 30, select Refactor-> Extract Constant (Extract a Constant, Extract a string or number from any position as a static global Constant. All characters or numbers that use this character are replaced with constants .)
1. Set the name for Constant name
2. Access modifier
3. Replace all occurrences of the selected expression with references to the constant. If this option is selected, the selected number is automatically replaced by this constant.
4. Qualify constant references with type name whether to use the type name to limit constant reference
8.10 EncapsulateField (encapsulation field)
I don't know what the difference is from "8.1 Self Encapsulate Field (Self-encapsulated value range )"
8.11 EncapsulateCollection (encapsulation set)
Setter/getter is not recommended for the Set (list, array) function. The former will overwrite the entire set directly, and it is not convenient for reverse lookup. The latter directly obtains control of all sets.
We recommend that you change it to the add/remove function to indirectly operate the set.
8.12 ReplaceRecordwithDataClass (replace records with data classes)
Encapsulate all data of the logic type into a new class.
8.13 Replace Type Code with Class (Replace Type Code with Class)
8.14 ReplaceTypeCodewithSubclasses (replace type code with subclass)
8.15 Replace the identifier with State/Strategy
Motivation: replace type code with State Object (Object specifically used to describe the State)
Practice
1. Use Self Encapsulate Filed to Encapsulate the type code itself.
2. Create a new class and name it based on the type code usage. This is the State Object.
3. Add subclasses for the newly created class. Each subclasses corresponds to a type code
4. An abstract query function is recommended in supperclass to return type code. Override this function in each subclass and return the exact type code.
5. Compile
6. Create a value field in the source class to save the new state object.
7. Adjust the type code query function in the source class to forward the query action to the state object.
8. Compile and test.
State Mode
8.16 Replace Subclass with Fields (Replace Subclass with value range)
Motivation: If constants are returned in each subclass, what is the significance of using interfaces and multiple subclasses.
Practice:
Chapter 9 simplified conditional expressions
9.1 Decompose Conditional (decomposition condition expression)
Motivation: excessive judgment usually results in reduced readability
Practice: extract conditions in if judgment as a method
9.2 merge lidate Conditional Expression (merge condition Expression)
Motivation: Sometimes a series of condition checks are found, and the check conditions are different, but the final behavior is consistent.
Practice: Merge multiple judgments and return the same value.
9.3 merge lidate Duplicate Conditional Fragments (merge Duplicate condition Fragments)
Motivation: if the code executed in both if and else is not put out of if and else, why not?
9.4 Remove Control Flag (Remove Control Flag)
Motivation: Java still supports the flag in the Condition Statement. Although it is not commonly used, it will be hard to understand if it is used.
9.5 Replace Nested Conditional with Guard Clauses (Replace Nested Conditional expressions with Guard statements)
Motivation: if both branches are normal, use if else. However, if some conditions are extremely rare, they should be checked separately and then directly returned. This is usually called (guard clocses)
You can check the level of if nesting by directly determining the returned form.
9.6 Replace Conditiona lwith Polymorphism (Replace conditional expressions with Polymorphism )??
Change swtich to a Polymorphism
Motivation: the most fundamental benefit of polymorphism is that if you need to take different behaviors based on different types of objects, polymorphism makes it unnecessary to write explicit conditional statements.
9.7 Introduce Null Object (introducing Null Object)
Motivation: in many cases, it is used to determine whether an object is empty. If it is empty, how can this problem be solved. Simply judge once. if it is null, a null object is returned, and the initial value is assigned to all fields in it. This will not cause exceptions, nor require too many if (value = null) judgments.
9.8 Introduce Assertion (introducing assertions)
Motivation: check must be a true condition. Do not misuse it. You can delete all assertions by using scripts during compilation.
Chapter 10 simplified function calls
10.1 Rename Method (renamed function)
Motivation: give a good name for a method for the program to understand. You can use the Eclipse outline View to view the method, just like reading an article.
Practice: Use Eclipse to select the method name, select Refactory-> Rename, or use the shortcut key Alt + Shift + R
You can rename any variables, classes, methods, package names, and folders, and modify them in all the places where they are used.
10.2 Add Parameter (Add Parameter)
10.3 Remove Parameter (Remove Parameter)
Motivation: as the system develops, adding and removing parameters or modifying the parameter location are common refactoring. The original parameters cannot meet the existing requirements, or some parameters are not used
Method: Use Eclipse to select the Method name, select Refactory-> Change Method SignatureAlt + Shift + C, or use the shortcut key
You can modify the method name, access permission, add and delete method parameters, modify the Parameter order, and add method exceptions.
10.4 Separate Query from Modifier (Separate the Query function from the modification function)
Motivation: cache the query results to speed up subsequent repeated queries.
10.5 Parameterize Method (parameters included in the function)
Motivation: the execution of multiple functions is the same smoothly, but each function may be able to extract these values to a single parameter because only one value is modified. Then, this method is reused to input different parameters.
10.6 Replace Parameter with Explicit Methods (Replace the Parameter with a definite function)
Motivation: If the function needs to determine the behavior through the parameter, simply create a new function for this parameter for processing.
10.7 Preserve Whole Object (keep Object complete)
Motivation: function parameters use multiple parameters of the same object. If you add or delete parameters, You need to modify all used parameters.
Practice: replace all parameters with this object, and the function internally takes the value from this object.
10.8 Replace Parameter with Methods (Replace parameters with functions)
Motivation: If a function parameter can be obtained through other functions, you do not need to pass it as a function parameter and directly call the function you want to pass in as a parameter in the function.
Too long parameter lists are not conducive to maintenance and understanding.
10.9 Introduce ParameterObject (introducing parameter objects)
Motivation: multiple parameters can be extracted as one type. Put these fields into the new data class and pass them to the data class.
10.10 Remove Setting Method (Remove the Setting function)
Motivation: some parameters do not need to be changed. You can delete the setter function to achieve the effect.
10.11 Hide Method (hidden function)
Motivation: hide some data and some behaviors cannot be triggered elsewhere. You can lower the function permission. Public-> private
10.12 Replace Constructor with Factory Method (Replace constructors with Factory functions)
Motivation: Cancel object creation with type code
10.13 Encapsulate Downcast (encapsulation downward transformation)
Motivation: return the Object and perform a downward transformation. If possible, return a fixed type.
10.14 Replace Error Code with Exception (Replace the Error Code with an Exception)
Motivation: some exceptions directly return numerical values. Why not throw new exception?
10.15 Replace Exception with Test (Replace Exception with Test)
Motivation: Exceptions cannot be a substitute for condition checks.
Chapter 4 Handling general relationships
11.1 PullUpField (Field Moving up)
11.2 PullUpMethod (function move up)
11.3 PullUpConstructorBody (constructor ontology moving up)
11.4 PushDownMethod (function downward)
11.5 PushDownField)
11.6 ExtractSubclass (extract subclass)
Chapter 2 large-scale reconstruction
12.1 Tease Apart Inheritance (combing and decomposing the Inheritance system)
Establish two inheritance systems and enable one of them to call the other through the delegation relationship.
12.2 Convert Procedural Design to Objects (converting Procedural Design into object Design)
Typical Case: The class has a long process function and a small amount of data, as well as the so-called sub-data object. There are no other functions except the data access function.
12.3 Separate Domain from Presentation (separating Domain and Presentation/display)
Separates domain logic (domain logic) to create an independent domain classes for them.
Motivation: the MVC mode separates the user interface code (view) from the domain logic (model.
12.4 Extract Hierarchy (Extract inheritance system)
Motivation: at the beginning of the design, only one class is required to complete the function. During implementation, two or three functions are found in one class. These new functions can be implemented as sub-classes.
Chapter 3 reconstruction, reuse and reality
13.1 realistic test
Only after the first version has been developed and the new features are added can we have a strong demand for refactoring.
13.2 why developers do not want to refactor their programs
1. Do not know how to refactor
2. Short-sighted, relatively high construction pressure
3. Code refactoring is a new workload
4. refactoring may introduce bugs
13.3 review the test of reality
13.4 reconstructed resources and references
13.5 from refactoring Lenovo to software reuse and technology Propagation