java - 单一职责原则的重构方法

标签 java refactoring single-responsibility-principle

我需要测试契约(Contract)义务程序。
我没有看到任何直接的方法来测试这个写的方法。它违反了 Single Responsibility Principle ,只是做了太多的事情。
我想知道如何安全地将以下职责提取到新方法或类中:

public void askUserPathAndWord() {

        BufferedReader bufferedReader = new BufferedReader(
                new InputStreamReader(System.in));
        String path;
        String whatFind;
        BlockingQueue<File> queue = new LinkedBlockingQueue<File>();

        try {
            System.out.println("Please, enter a Path and Word"
                    + "(which you want to find):");
            System.out.println("Please enter a Path:");
            path = bufferedReader.readLine();
            System.out.println("Please enter a Word:");
            whatFind = bufferedReader.readLine();

            if (path != null && whatFind != null) {

                File endOfWorkFile = new File("GameOver.tmp");
                CountDownLatch latch = new CountDownLatch(2);

                FolderScan folderScan = new FolderScan(path, queue, latch,
                        endOfWorkFile);
                FileScan fileScan = new FileScan(whatFind, queue, latch,
                        endOfWorkFile);

                Executor executor = Executors.newCachedThreadPool();
                executor.execute(folderScan);
                executor.execute(fileScan);

                latch.await();
                System.out.println("Thank you!");
            } else {
                System.out.println("You did not enter anything");
            }

        } catch (IOException | RuntimeException e) {
            System.out.println("Wrong input!");
            e.printStackTrace();
        } catch (InterruptedException e) {
            System.out.println("Interrupted.");
            e.printStackTrace();
        }
    }

问题:
我们如何能够安全地执行后续步骤:

  • 向用户询问单词和路径;
  • 给定一个词,创建一个 FileScan 使用正确的参数(工厂);
  • 给定一条路径,创建一个 具有正确参数的 FolderScan(工厂);
  • 给定两个 runnables 和一个闩锁,创建一个 ExecutorService,将它们排队,然后等待 在门闩上。

最佳答案

与大多数重构一样,安全的第一步是测试当前的方法。 然后将代码重构为具有必要职责的逻辑组——在整个过程中,您之前编写的测试不应中断。 然后你可以放弃你原来的测试,它测试了太多的东西,支持只对你编写的新代码做出断言的测试

关于java - 单一职责原则的重构方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15112857/

相关文章:

javascript - 如果功能在主要目的之上记录错误,是否违反了 SRP?

java - 当我设置类实例时,我的 Android 应用程序崩溃了

version-control - 是否有 “understands” 常见重构的 3 路合并工具?

python - 是否有 IDE/实用程序来重构 Python * 导入以使用标准 module.member 语法?

asp.net-mvc - ASP.NET MVC 向最终用户显示操作成功

c# - SRP 和很多类(class)

Java - 在对象的ArrayList中搜索字符串

java - hdfc 网上银行页面中客户 ID 的 xpath [Selenium Webdriver] [JAVA]

java - 如何打开电子邮件客户端并在java中自动附加文件

eclipse - 如何使用 Eclipse 重构工具并通过 Subclipse 与 SVN 保持同步?