跳至主要內容
IDEA重构技巧:更改签名

IDEA重构技巧:更改签名

来看看如何安全地更改类或方法的签名。

我们在 BugReport 中的方法 binaryStrings 接受一个 String 参数:

public boolean binaryStrings(String b) {
    Stack<Character> s = new Stack<>();
    for (char c : b.toCharArray())
        if (s.empty() || !s.peek().equals(c))
            s.push(c);
        else
            s.pop();
    return s.empty();
}

DD编辑部原创大约 2 分钟IntelliJ IDEAIntelliJ IDEA
IDEA重构技巧:提取常量

IDEA重构技巧:提取常量

在代码库中,通常建议使用常量而不是文字值,那么我们来看看如何重构代码以引入常量

public static boolean beautifulBinaryStrings(String s) {
    while (!s.equals(s = s.replaceAll("AA|BB", ""))) {
        System.out.println(s);
    }
    return s.isEmpty();
}

DD编辑部原创小于 1 分钟IntelliJ IDEAIntelliJ IDEA
IDEA重构技巧:提取字段

IDEA重构技巧:提取字段

您可以通过此重构引入或提取字段并将其初始化。

我们的 ViewImpl 类中的方法 getItemsList 使用常量 0 和 4 来获取一个列表的子集。

public class ViewImpl implements View {
   @Override
   public List<Integer> getItemsList() {
       return List.of(1, 2, 3, 4, 5).subList(0,4);
   }
}

DD编辑部原创小于 1 分钟IntelliJ IDEAIntelliJ IDEA
IDEA重构技巧:提取方法

IDEA重构技巧:提取方法

Extract Method 重构可以使您的方法更短、更易读。

public boolean binaryStrings(String b) {
    Stack<Character> s = new Stack<>();
    for (char c : b.toCharArray())
        if (s.empty() || !s.peek().equals(c))
            s.push(c);
        else
            s.pop();
    return s.empty();
}

DD编辑部原创大约 1 分钟IntelliJ IDEAIntelliJ IDEA
IDEA重构技巧:提取参数

IDEA重构技巧:提取参数

通过 Extract Parameter 重构,您可以在方法中选择一个常量或表达式,并将其定义为参数传递给方法。 在本示例中,我们还为 getItemsList 方法引入了第二个字段,名为 toIndex

public class ViewImpl implements View {
   private final int fromIndex;
   private final int toIndex;

   public ViewImpl() {
       fromIndex = 0;
       toIndex = 4;
   }

   public List<Integer> getItemsList() {
       return List.of(1, 2, 3, 4, 5).subList(fromIndex, toIndex);
   }
}

DD编辑部原创大约 1 分钟IntelliJ IDEAIntelliJ IDEA
IDEA重构技巧:提取变量

IDEA重构技巧:提取变量

我们也可以根据需要提取变量

有时,我们可以将表达式移到一个适当命名的变量中,使代码更易读。

public ContextActionsWithAltEnter(double cityPopulation) {
    if (cityPopulation > 0x1.2016eb678a2p43 && cityPopulation < 987677.8) {
        if (cityPopulation % 5 == 0) {
            this.cityPopulation /= 2;
        }
    }
    this.cityPopulation = cityPopulation;
}

DD编辑部原创大约 1 分钟IntelliJ IDEAIntelliJ IDEA
IDEA重构技巧:内联方法

IDEA重构技巧:内联方法

内联方法重构 是 Extract Method 重构的逆转。

我们可以在 macOS 上使用快捷键 ⌥⌘N ,或者在 Windows/Linux 上使用 Ctrl+Alt+N 来内联刚刚创建的方法 manipulateStack


DD编辑部原创小于 1 分钟IntelliJ IDEAIntelliJ IDEA
IDEA重构技巧:安全删除

IDEA重构技巧:安全删除

如果您不想再在项目中使用某个文件或符号,您应该把它安全删除

选择要删除的文件或类,然后使用 ⌘⌦,或者在 Windows/Linux 上使用 Alt+Delete。 IntelliJ IDEA 在确保资源可被安全删除之后才会将其删除。


DD编辑部原创小于 1 分钟IntelliJ IDEAIntelliJ IDEA
最常用的IntelliJ IDEA快捷键(含Windows、MacOS双版本)

最常用的IntelliJ IDEA快捷键(含Windows、MacOS双版本)

本文Mac快捷键风格为Intellij IDEA Classic,如不是则首先需要在Preferences中切换

一. Mac符号缩写

Mac电脑键盘的符号缩写说明如下,下面可能会用到


郭Albert大约 8 分钟IntelliJ IDEAIntelliJ IDEA
2
3
4
5
...
7