IDEA代码重构技巧--抽取+内联

本文详细介绍IDEA中如何通过快捷键进行变量抽取(CTRL+ALT+V)、参数抽取(CTRL+ALT+P)、函数抽取(CTRL+ALT+M),以及内联操作(CTRL+ALT+N)来提升代码质量。实例演示和实用场景让你轻松掌握重构技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

IDEA代码重构技巧--目录页

1. 抽取

在做代码重构时,可能发现我们需要将变量,参数做抽取,或者某个方法过长,需要将这个方法中相同逻辑的代码块抽取出一个独立的函数,这时候就需要使用抽取,抽取有三类:

  1. 抽变量,IDEA快捷键 CTRL+ALT+V
  2. 抽参数,IDEA快捷键 CTRL+ALT+P
  3. 抽函数,IDEA快捷键 CTRL+ALT+M

示例代码:

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);
    }
}

1.1. 抽变量

    选中可以被抽取的变量,例如示例函数extractVariable中的this.testInt,键入CTRL+ALT+V

1.2. 抽参数

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

1.3. 抽函数

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

2. 内联

    在做代码重构时有时会发现有的变量或者函数没必要被独立的抽取出来,增加了代码的阅读成本,同时也不利于后续的优化,此时我们需要使用内联简化代码
    例如:变量只使用了一次,但是被独立的抽取出来了,这时可以使用内联将变量替换到调用的位置。函数内容很短,逻辑很简单,只被调用了一次,而且预期未来不会有别的地方调用,这时可以使用内联将函数内容替换到调用位置。

/**
 * @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";
    }

}

2.1. 内联变量

    选中需要被内联的变量,键入CTRL+ALT+N

 2.2. 内联函数

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值