Details of several patterns of Java code refactoring

  • 2020-04-01 02:18:20
  • OfStack

There are three main refactoring patterns for Java code:

Renaming method reconstructs pattern, introducing explanatory variable reconstructs pattern, replacing temporary variable reconstructs pattern with query

The following steps are recommended for renaming methods to refactor the pattern :

1. Create a method with a new name

2. Copy the method body of the old method into the new method

3. The body of the old method is changed to call the new method

4. Change all references to old methods to refer to new methods

5. Remove old methods

The steps of introducing explanatory variables to reconstruct the pattern are relatively simple, as follows:

Declare a local variable and initialize it to the part of the expression that needs to be replaced

2. For complex expressions, replace the parts that need to be replaced with new local variables

3. Repeat the process for the rest of the expression

The steps for reconstructing the schema with queries instead of temporary variables are as follows:

1. Find local variables that have been assigned only once

2. Declare the local variable as final and recompile (to ensure that the variable is indeed only assigned once)

3. Copy the expression to the right of the equal sign of the assignment statement and modify it to the method body of a new method

4. Change the right hand side of the equal sign of the assignment statement to the call to the new method

5. Replace all use of the local variable with calls to the new method

6. Remove assignment statements and declarations of local variables


Related articles: