更新时间:2023-10-16 GMT+08:00
分享

引入参数对象

此重构允许您将方法的参数移动到新的包装类或某些现有的包装类。所有参数的用法都将替换为对包装类的相应调用。

执行重构

  1. 在代码编辑器中,将光标放置在要提取到包装类的参数上。
  2. 在主菜单或编辑器上下文菜单中,选择Refactor>Introduce Parameter Object
  3. 在打开的Introduce Parameter Object对话框中,提供重构选项。

    • Keep method as delegate:选择将原始方法保留为新创建方法的委托。
    • Parameters Class: 在此区域中,选择是要创建新的包装参数类、在当前包装参数类中创建内部类,还是使用某些现有类。
    • Name:输入包装后参数的名称。
    • Parameters to Extract: 在此区域中,选中要提取到包装参数类的参数旁边的复选框。

  4. 单击Refactor以应用重构。

示例

例如,让我们将helloworld参数提取到TextContainer内部类,以使生成的generateText方法调用将包含对TextContainer对象的调用。

重构前

class ExtractParameterObject {
    public static void main(String[] args) {
        System.out.println(generateText("Hello", "World!"));
    }

    private static String generateText(String hello, String world) {
        return hello.toUpperCase() + world.toUpperCase();
    }
}

重构后

class ExtractParameter {
    public static void main(String[] args) {
        System.out.println(generateText(new TextContainer("Hello", "World!")));
    }

    private static String generateText(TextContainer textContainer) {
        return textContainer.getHello().toUpperCase() + textContainer.getWorld().toUpperCase();
    }

    private static class TextContainer {
        private final String hello;
        private final String world;

        private TextContainer(String hello, String world) {
            this.hello = hello;
            this.world = world;
        }

        public String getHello() {
            return hello;
        }

        public String getWorld() {
            return world;
        }
    }
}
分享:

    相关文档

    相关产品