跳至主要內容

IDEA重构技巧:提取参数

DD编辑部原创IntelliJ IDEAIntelliJ IDEA大约 1 分钟

IDEA重构技巧:提取参数

通过 Extract Parameter 重构open in new window,您可以在方法中选择一个常量或表达式,并将其定义为参数传递给方法。 在本示例中,我们还为 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);
   }
}

getItemsList 方法中,您可以将表达式 List.of(1,2,3,4,5) 作为参数传递给此方法。 方法参数的类型与所选表达式的类型相同。

您也可以选中 Delegate via method overloading 复选框,以保留原始方法并允许引入第二个方法。 这意味着任何一个方法都可以根据调用者来使用。

Extract parameter 可以帮助您将表达式移到最合理的位置,使方法或方法调用更易读。 使用易于理解的参数名称也有助于提高可读性。

好了,今天的分享就到这里,如果这个小技巧对你有用,那就帮忙点赞、在看、分享、关注,四连支持一下吧!

如果你觉得这个系列还不错,可以关注我在连载的这个专栏:玩转IntelliJ IDEA,分享各种使用技巧与好用插件!

上次编辑于:
贡献者: 程序猿DD