在做代码重构时,可能发现我们需要将变量,参数做抽取,或者某个方法过长,需要将这个方法中相同逻辑的代码块抽取出一个独立的函数,这时候就需要使用抽取,抽取有三类:
示例代码:
- package com.coline.extract;
-
- /**
- * @author: Coline
- * @ClassName: ReconsitutionParam
- * @Date: 2022/8/20 10:34
- * @Description: 抽取验证
- * 抽变量 CTRL+ALT+V
- * 抽参数 CTRL+ALT+P
- * 抽函数 CTRL+ALT+M
- */
- public class ReconsitutionParam {
- private int testInt;
- private String testStr;
-
- /**
- * @Description: 抽取变量,选中this.testInt,键入CTRL+ALT+V
- */
- public void extractVariable() {
- System.out.println("testInt: " + this.testInt + "testStr: " + this.testStr);
- }
-
- /**
- * @Description: 抽取参数,选中函数第一行的变量testStr,键入CTRL+ALT+P
- */
- public void extractParam() {
- String testStr = this.testStr;
- System.out.println("testStr: " + testStr);
- }
-
- /**
- * @Description: 抽取函数,选中函数第一行的String testStr = this.testStr; ,键入CTRL+ALT+M
- */
- public void extractMethod() {
- int testInt = this.testInt;
- System.out.println("testInt: " + testInt + "testStr: " + testStr);
- }
- }
选中可以被抽取的变量,例如示例函数extractVariable中的this.testInt,键入CTRL+ALT+V

选中需要被抽取的参数,例如示例函数extractParam中的变量testStr,键入CTRL+ALT+P,就会将变量抽取到方法参数中

选中需要被抽取的代码块,键入CTRL+ALT+M,就会将变量抽取到方法参数中

在做代码重构时有时会发现有的变量或者函数没必要被独立的抽取出来,增加了代码的阅读成本,同时也不利于后续的优化,此时我们需要使用内联简化代码
例如:变量只使用了一次,但是被独立的抽取出来了,这时可以使用内联将变量替换到调用的位置。函数内容很短,逻辑很简单,只被调用了一次,而且预期未来不会有别的地方调用,这时可以使用内联将函数内容替换到调用位置。
- /**
- * @author: Coline
- * @ClassName: ReconsitutionInline
- * @Date: 2022/8/20 12:07
- * @Description: 重构-内联
- * CTRL+ALT+N
- */
- public class ReconsitutionInline {
- private int testInt;
- private String testStr;
-
- /**
- * 验证内联变量
- * 选中变量,键入CTRL+ALT+N
- */
- public void inlineVariable() {
- int testInt = this.testInt;
- System.out.println("testInt: " + testInt + "testStr: " + this.testStr);
- }
-
- /**
- * 验证内联函数
- * 选中待内联函数,键入CTRL+ALT+N
- * @return
- */
- public String inlineMeth() {
- return inlineMethTmp();
- }
-
- public String inlineMethTmp() {
- return "I am inline Meth";
- }
-
- }
选中需要被内联的变量,键入CTRL+ALT+N

选中需要被内联的函数,键入CTRL+ALT+N
