Extraction Method of Java Code refactoring

The extraction method of Java Code refactoring is to extract part of the code logic as an independent method to improve the readability, maintainability and reusability of the code. Here is an example to illustrate when method extraction and refactoring are required, as well as the code example after refactoring. Assuming we have a program for calculating employee annual salary, which includes the following code snippet: double calculateYearlySalary(String name, double monthlySalary) { double yearlySalary; if (monthlySalary < 0) { throw new IllegalArgumentException("Monthly salary cannot be negative."); } If (name==null | | name. isEmpty()){ throw new IllegalArgumentException("Name cannot be null or empty."); } //Assuming there is other logic yearlySalary = monthlySalary * 12; return yearlySalary; } The above code checks the validity of the parameters before calculating the annual salary, and there are also some other logic, such as calculating taxes. However, we found that the logic of parameter checking (if statement) occupies a large number of lines of code, and it repeats in many places, resulting in Duplicate code duplication and verbosity. At this point, method extraction can be considered to optimize the code. We can extract the logic of parameter checking as an independent method, as follows: void validateInputs(String name, double monthlySalary) { if (monthlySalary < 0) { throw new IllegalArgumentException("Monthly salary cannot be negative."); } If (name==null | | name. isEmpty()){ throw new IllegalArgumentException("Name cannot be null or empty."); } } Then, call the newly extracted method before calling the original method, as shown in the following example: double calculateYearlySalary(String name, double monthlySalary) { validateInputs(name, monthlySalary); double yearlySalary; //Assuming there is other logic yearlySalary = monthlySalary * 12; return yearlySalary; } By using the extraction method, we make the original method more concise and clear, and by extracting the logic of parameter checking into an independent method, we can improve the readability and maintainability of the code. At the same time, the extracted methods can also be reused elsewhere, avoiding duplicate code writing. Summary: Method extraction and refactoring can be used when reusing a segment of the same or similar code logic. By extracting an independent method to achieve code reuse and logical organization, the readability, maintainability, and reusability of the code can be improved.