"Refactoring" Reading notes and Eclipse refactoring function use

Source: Internet
Author: User
Tags modifier

Chapter II Reconstruction Principles
What is refactoring?
Refactoring (noun): an adjustment to the internal structure of software to improve its understanding and reduce its cost of modification without changing the "observed behavior of the software".
Refactoring (verb): Use a series of refactoring guidelines (techniques) to adjust their structure without altering [the observed behavior of the software].

Two hats: Add new features and refactoring, not at the same time.

Why refactor?
Improved software design: possible design at the beginning, based on existing needs, is the world's best design. However, there may be many additions and deletions in the process, the original design has not satisfied the existing requirements.
Make the software easier to understand:
Often adding comments is not necessarily a good choice, because the code may be modified by someone else, and the comment will be ignored. The follow-up people are looking at the comments as a hindrance to understanding.
The program is for people to read, not to write to the computer to see.
Find BUG: Refactoring process requires grooming process, can find multiple functions, or multiple iterations coupled to the bug
Improve programming Speed: Easy to understand, itself is to improve, new features of the development speed.


When to refactor?
When adding features, when modifying errors, when reviewing code,

The challenge of refactoring?
database, modifying interfaces,

When does refactoring not change?
Code logic is confusing, nothing new can be added at all, and it may need to be completely rewritten in some cases, but it is recommended to split into smaller modules and then step through refactoring and rebuilding.
The project is nearing the deadline.

Design after the development, but there is no need to find the most flexible design solutions and worry. Just choose the most reasonable plan, implement and then try, verify, feedback and revise in practice.
Because it is never possible to anticipate subsequent changes in the early stages, and it is not possible to design with all the details in mind, nor is it necessary.

Refactoring and performance?
Three different ways
Time budgeting (evaluating each task execution time and execution chain)
Continuous attention to the law (note in the process, but sometimes it slows down the development, or the program is difficult to understand)
Late development (focus on relatively large performance consumption)


The origins of refactoring?
1980 Smalltalk



Chapter III Bad taste of code
3.1 Duplicated code (duplicate codes)
Repetitive logic functions (same class, multiple subclasses, non-homogeneous)
3.2 Long method (Long function)
A function has only one function, in which case, rarely more than 15 rows
The more functions within a method, the more difficult it is to reuse. or redundant multiplexing.

3.3 Large Class (too Large)
3.4 Long Parameter list (too long parameter column)
Or too many global variables, you can divide the changes into new classes.

3.5 Divergent Change (Divergent)
There are too many functions to be hosted in a class.

3.6 Shotgun Surgery (Shotgun-Modified)
The development of a function needs to be involved in many areas of modification. Why not put a type of functionality into a class?

3.7 Feature Envy (attachment complex)
Put together things that are always changing together. The behavior of data and reference to these data always changes together.

3.8 Data Clumps (Slime Regiment)
There are too many or too few data in a class to be distributed across multiple classes

3.9 Primitive Obsession (basic type Paranoia)
Do not want to put a type of data source into a new data class

3.10 Switch statements (switch horror appearances)
Whether to use polymorphic substitution

3.11 Paralle linheritance Hierarchies (parallel succession system)
Subclasses have functions that are extracted into the parent class. Or simply create a new class to use in creating an object reference.

3.12 Lazy Class (redundant Class)
itself very complex, after refactoring the function is in too little, or very few places to call, simply to remove this class.

3.13 Speculative generality (rhetoric of the future)

Excessive design, said to be easy to expand later, but may be a long time is just a single use.


3.16 Middle man (Middleman)
Half of a class's functions are delegated to other classes.

3.14 temporary field (confusing temporary field)
Scattered data, pumped into a new data class


3.15 message Chains (over-coupled messaging chain)
A function of a object needs to be called F-E, D-C, B. Finally, there is the desired function in E, whether the process can be extracted directly together, a directly invoke the extracted object. (Public object)

3.17 inappropriate intimacy (contempt relationship)
Excessive invocation between the parent class and the subclass, or two classes, too many calls to each other, simply put the method of excessive invocation together.

3.18 Alternative Classeswith Different Interfaces (similar class)
Similar to a class or function


3.19 Incomplete Library class (imperfect libraries)
To add an extension to a class library

3.20 Data Class (childlike)
3.21 refused bequest (rejected bequest)
Subclasses of some classes that do not require the functionality of their parent class


3.22 Comments (Too much comment)




Sixth chapter re-organization function
6.1 Extract Method (refinement function)
Motivation:
The function is more granular, and the chances of reuse are greater.
The high-level function reads like a series of annotations.
The replication of functions is also easier
Practice:
Eclipse Select a few lines of code, choose Refactory---Extract Method or use shortcut keys (Alt + Shift + M)
Arbitrarily select a piece of code, automatically convert to a function, automatically add the parameter return type.

6.2 Inline method (inline function)
Motivation: Sometimes it may be found that using code directly in a function is easier to understand than extracting a function.
Practice:
Eclipse Select the function name, select Refactory-+ inline or use the shortcut key ALT + Shift + I
Replace the place where you call this function directly with the contents of this function. Select any function to use this feature. (with all invocations and only the selected invocation two options)

6.3 inlinetemp (Inline temp variable)
Motivation: Some temporary variables may be reconstructed by impressions
Directly modify the use of variables, and delete temporary variables

6.4 Replacetempwithquery (replace temporary variable with query)
Motive: block the extraction function and put the calculation into the fixed function

6.5 Introduceexplainingvariable (introduction of explanatory variables)
Eclipse Select expression, select Refactory---Extract Local variable or use the shortcut key ALT + Shift + L
Usually used for expressions, to extract one of the local variables, such as 3 + 5 is extracted to int i = 3;

6.6 splittemporaryvariable (Decomposition temp variable)
Motive: A temporary variable is assigned only once, if it is assigned more than once to assume more than one duty. It's easy to confuse the reader.

6.7 Removeassignmentstoparameters (Remove the assignment to the parameter)
Value Passing (pass-by-value)
Http://www.blogjava.net/heis/archive/2009/04/23/267256.html
Reference Delivery (pass-by-refrence)


6.8 Replacemethodwithmethodobject (Replace function with function object)
If you find that a function has a large number of temporary variables that could not be broken into a fine-grained function, you can put this function into a new class, so that the temporary variables in the function is a global variable in this class, you can arbitrarily extract fine-grained functions.


6.9 Substitutealgorithm (Replacement algorithm)






The seventh chapter moves the characteristics between objects


It is very important to decide where to put your responsibilities during the object design process. Usually very distressed, but the use of refactoring can change their original design.

7.1 Move Method (removal function)
Motivation: There are too many coupling behaviors between the two classes so that the two classes can be made neat by moving the function.
Practice:
Set the function you want to move to static so that you can see all references to the current class global variables, methods in this method, and pass those parameters that are replaced by functions.
Then use Eclipse to select the function name, choose Refactory, move, or use the shortcut key (Alt + Shift + V) to move the field to another class, move the class to another package

7.2 Move field (moving fields)
Motivation: As the system develops, it discovers that it needs new classes and needs to drag the original job responsibilities into 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, move the class to another package

7.3 Extract Class (refinement)
Motivation: A lot of data is scattered around, and logically divided data can be put into one category.
Practice: Use Eclipse to select a field, select Refactory-Extract Class
To refer to the new class for all the selected fields, you can choose to create a new file or make the inner class

7.4 Inline class (inline Class)
Motivation: There is not much behavior in the class, as opposed to extract class.

7.5 Hide Delegate (hide "delegate relationship")
Motivation: Reduce the coupling between classes through a "delegate relationship."

7.6 Remove middleman (remove middleman)
Contrary to 7.5

7.7 Introduce Foreign Method (introducing an additional function)
Motive: All the parameters of the function are using the value of the same data object, simply passing the data object directly into the function.


7.8 Introduce local Extension (introduction of native extensions)
Motivation: Some places that cannot directly modify the source code need to add new support.
Practice: Inherit, and then add functionality.




Eighth re-organization of data


8.1 Self encapsulate Field (from package domain)
Motivation: It is always controversial to use fields directly or add setter/getter, and it is recommended to use the fields directly when you must use Setter/getter to change automatically.
Practice:
The Eclipse refactoring tool can automate such operations.
Select Properties in Eclipse, choose Refactor-encapsulate Filed.

1. Set the Getter/setter name
2. How to modify using this field, use setter and getter (replace reference with set and get method, keep field refrence keep original field reference unchanged), OK
3. Insert new method after insertion position

8.2 Replace data value with object (instead of values in objects)
Motivation: The initial development may only need simple data items can be done, as the development of line data items more and more, at this time can be the data values into objects.
Practice:
The Eclipse refactoring tool can automate such operations.
In the class where you want to extract the fields, Eclipse Select Refactor-Extract class.
1. Class name Specifies the new data name
2. Destination create a new class file, or use an internal class form
3. Select field for extracted class to check the extraction fields, edit the type and field names to the right
4. Field name specifies the names of the fields in the current class that use this new data object.


8.3 Change value to Reference (changing values to reference objects)
Motivation:
Practice:

8.4 Change Reference to value (changing the Reference object to a value object)

8.5 Replace array with object (replaces arrays with objects)
Motivation:
Practice:
string[] person = new STRING[3];
Person[0] = "18";
PERSON[1] = "name";


Post-modification effects

8.6 duplicateobserveddata (copy "monitored data")
GUI multiple display values are associated or identical (place this data in one place)

8.7 changeunidirectionalassociationtobidirectional (change one-way Association to Bidirectional Association)
A reference B, want to modify to a reference b,b also reference a

8.8 changebidirectionalassociationtounidirectional (change bidirectional Association to one-way association)
Contrary to 8.7

8.9 replacemagicnumberwithsymbolicconstant (replacing magic numbers with literal constants)
Motive: The magic number is the direct use of numbers, the problem is that the other people do not know what this magic number means, why it must be this number, may use the same logical number of magic numbers, only modify a place can not forget the changes elsewhere.
Practice:
The Eclipse refactoring tool can automate such operations.
Eclipse selects the magic number that needs to be extracted as a constant, here is the number 30 selected, select Refactor---Extract Constant (extract the constant, the arbitrary position of the string or the number is extracted to a static global constant. Any use of this character or number will be replaced with a constant. )

1. Constant Name Settings
2. Access modifier setting permissions
3. Replace all occurrences of the selected expression with references to the constant if checked, it will be replaced automatically so the number is selected where this constant
4. Qualify constant references with type name to qualify a constant reference


8.10 Encapsulatefield (Package field)
I don't see any difference between "8.1 self encapsulate Field (from package domain)"

8.11 Encapsulatecollection (Package collection)
The collection (list, array) function does not recommend providing Setter/getter, which overwrites the entire collection directly and does not facilitate reverse lookups. The latter directly obtains control of all sets.
It is recommended that you modify the Add/remove function to manipulate the collection indirectly.

8.12 Replacerecordwithdataclass (replacing records with data classes)
Encapsulates all data of a logically typed type into a new class.

8.13 Replace type Code with class (substituting class code)

8.14 replacetypecodewithsubclasses (replace type code with sub-class)

8.15 Replace identification code with STATE/STRATEGY
Motive: Replace type code with state object, which is specifically used to describe the status
Practice
1. Use the self encapsulate Filed to encapsulate the type code itself.
2. Create a new class, named according to the type code purpose. This is the state Object.
3. Add subclasses for the newly created class, and each subclasses corresponds to a type code
4. In Supperclass, an abstract query function is recommended for returning type code. This function is written in each subclass and returns the exact type code.
5. Compiling
6. Create a value domain in the source class to save the new state object.
7. Adjust the function in source class that is responsible for querying the type code, and forward the query action to the State object
8. Compile, test.


State mode

8.16 Replace subclass with Fields (replaces subclasses by range)
Motivation: If a constant is returned in each subclass, it is much more meaningful to use the interface with multiple subclasses.
Practice:





Nineth. Simplifying conditional expressions

9.1 Decompose Conditional (decomposition condition expression)
Motivation: Too much judgment often leads to decreased readability
Practice: Extracting conditions from the if judgment as a method

9.2 Consolidate Conditional expression (combining conditional expressions)
Motivation: Sometimes a set of condition checks is found, and the conditions are different, but the final behavior is consistent.
Practice: Combine multiple judgments to return the same value.

9.3 Consolidate Duplicate Conditional Fragments (merge duplicate conditional fragments)
Motivation: If the code that executes in the IF and else, why not just put it outside of the IF and else?

9.4 Remove Control flag
Motivation: Java still supports markup in conditional statements, although less commonly used, but can cause a program to be difficult to understand if used.

9.5 Replace Nested Conditional with guard clauses (replaces nested conditional expressions with guardian statements)
Motivation: If the two branches are normal behavior, you should use if else. However, if certain conditions are extremely rare, the conditions should be checked separately and then returned directly. This is commonly called (Guardian Statement guard clauses)
You can check the hierarchy of if nesting by directly judging the form of the return.

9.6 Replace Conditiona Lwith polymorphism (polymorphic substitution conditional expression)??
Change the Swtich to polymorphic form
Motivation: The fundamental benefit of polymorphism is that if you need to behave differently depending on the class of the object, polymorphism makes it unnecessary to write explicit conditionals.

9.7 Introduce null object (introduction of Null objects)
Motivation: Many places determine whether an object is empty, how to handle it, and how to handle it without being empty. Simply judge once, if NULL returns a null object, it is internally assigned the initial value for all fields, which does not result in an exception, nor does it require too much if (value = = null) judgment.

9.8 Introduce assertion (introduction assertion)
Motive: Check must be true condition. Do not misuse, you can delete all assertions through the script at compile time.









Tenth chapter simplified function invocation

10.1 Rename Method (function renaming)
Motivation: A good name for a method to facilitate the understanding of the program. You can view methods through the Eclipse outline view, like reading articles.
Practice: Use Eclipse to select the method name, select Refactory-Rename or use the shortcut key ALT + Shift + R
You can rename any variable, class, method, package name, folder, and all the places you use will be modified uniformly.

10.2 Add Parameter (add parameter)
10.3 Remove Parameter (remove parameters)
Motivation: As the system develops, adding and removing parameters, or modifying the location of the parameters, is a common refactoring. The original parameters do not meet the existing requirements, or some parameters are not used
Practice: Use Eclipse to select the method name, choose Refactory, change method Signaturealt + Shift + C, or use shortcut keys
Operation of the method, you can modify the method name, access permissions, increase the deletion method parameters, modify the parameter order, add method exception

10.4 Separate query from Modifier (separating the query function from the modified function)
Motivation: The query results are cached, subsequent repeated queries can greatly accelerate the speed.

10.5 parameterize Method (make function carry parameter)
Motivation: Multiple functions perform as smoothly as possible, but each of these values can be extracted to a parameter by simply modifying a value, and then multiplexing this method multiple ways to pass in different parameters.

10.6 Replace Parameter with Explicit Methods (replace parameter with explicit function)
Motivation: If the function needs to determine what behavior to do by parameters, simply create a new function for this parameter to process.

10.7 Preserve Whole Object (keep objects intact)
Motivation: The function parameter uses multiple parameters of the same object, and if you add or delete parameters, you need to modify all the places that are used.
Practice: Replace all parameters with this object, and the function internally values this object.

10.8 Replace Parameter with Methods (replace parameter with function)
Motivation: If the parameters of a function can be obtained by other functions, it is not necessary to pass it as a function parameter, directly inside the function call the function that it wants to be passed in as a parameter.
A long list of parameters is not conducive to maintenance and understanding.


10.9 Introduce Parameterobject (introduction of Parametric objects)
Motive: Put multiple parameters, if can be extracted as one type, put these fields into the new data class, and then pass this data class.


10.10 Remove Setting Method (remove SetPoint function)
Motivation: Some parameters do not need to be changed, you can delete their setter function to achieve the effect.


10.11 Hide Method (hidden function)
Motivation: To hide certain data, and certain behaviors cannot be triggered elsewhere. You can turn down the function's permissions. Public, private


10.12 Replace Constructor with Factory Method (replace constructor with factory function)
Motive: Cancels creating an object with type code


10.13 Encapsulate Downcast (package downward transition)
Motive: Returns an object and then transitions down if a fixed type can be returned directly.


10.14 Replace error code with Exception (an exception is substituted for the fault code)
Motivation: Some exceptions directly return values, why not simply throw new exception?


10.15 Replace Exception with test (replacing exceptions with tests)
Motivation: Exceptions cannot be substitutes for conditional checks






The 11th chapter deals with the generalization relationship


11.1 Pullupfield (field move up)
11.2 Pullupmethod (function Move up)
11.3 Pullupconstructorbody (The constructor body moves up)
11.4 Pushdownmethod (function Move Down)
11.5 Pushdownfield (field Move Down)
11.6 Extractsubclass (Refining sub-category)


The 12th chapter of large-scale reconstruction


12.1 Tease Apart Inheritance (combing and decomposing the inheritance system)
Build two inheritance systems and let one of them call another by delegating relationships.

12.2 Convert procedural design to Objects (convert the process to object design)
Typically, there are long process functions and very little data in class, and so-called sub-data objects, where there are no functions outside of the data access function.

12.3 Separate domain from Presentation (separating domains and representations/displays)
Isolate domain logic, and create separate domain classes for them
Motivation: The MVC pattern separates the user interface code (view) from the domain logic (model models).

12.4 Extract Hierarchy (Refining inheritance system)
Motivation: At the beginning of the design only a class completion function is required, and a class is found to have 2 or 3 functions in the implementation process. These new features can be implemented as subclasses.




The 13th chapter reconstruction, Reuse and reality


13.1 Test of reality
Only after the development of a version, once again on the basis of new features, will be strong demand for refactoring.


13.2 Why developers are reluctant to refactor their programs
1. Don't know how to refactor
2. Short-sighted, the period of pressure is relatively large
3. Code refactoring is a new workload
4. Refactoring may introduce bugs


13.3 re-discussion on the test of reality


13.4 Refactoring Resources and references


13.5 from the reconstruction of Lenovo to software reuse and technology diffusion


"Refactoring" Reading notes and Eclipse refactoring function use

Related Article

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.