简体   繁体   English

'巧合编程'练习:Java文件编写器

[英]'Programming by Coincidence' Excercise: Java File Writer

I just read the article Programming by Coincidence . 我刚刚阅读了“ 巧合编程 ”一文。 At the end of the page there are excercises. 在页面的末尾有练习。 A few code fragments that are cases of "programming by coincidence". 一些代码片段是“巧合编程”的案例。 But I cant figure out the error in this piece: 但我无法弄清楚这篇文章中的错误:

This code comes from a general-purpose Java tracing suite. 此代码来自通用Java跟踪套件。 The function writes a string to a log file. 该函数将字符串写入日志文件。 It passes its unit test, but fails when one of the Web developers uses it. 它通过了单元测试,但是当其中一个Web开发人员使用它时失败。 What coincidence does it rely on? 它依赖什么巧合?

  public static void debug(String s) throws IOException {
    FileWriter fw = new FileWriter("debug.log", true);
    fw.write(s);
    fw.flush();
    fw.close();
  }

What is wrong about this? 这有什么问题?

This code relies on the fact that there is a file called debug.log that is writable in the application's executing directory. 此代码依赖于一个名为debug.log的文件,该文件在应用程序的执行目录中是可写的。 Most likely the web developer's application is not set up with this file and the method fails when he tries to use it. 很可能Web开发人员的应用程序没有使用此文件设置,并且该方法在尝试使用它时失败。

A unit test of this code will work because the original developer had the right file in the right place (and with the right permissions). 此代码的单元测试将起作用,因为原始开发人员在正确的位置(并具有正确的权限)具有正确的文件。 This is the coincidence that allowed the unit test to succeed. 这是允许单元测试成功的巧合。

Interesting tidbit. 有趣的花絮。 Ideally, resources must be pulled from the classpath. 理想情况下,必须从类路径中提取资源。 However, there is no end to human studpidity though. 然而,尽管如此,人类的顽固是无止境的。 What would happen if the file was present in test environment's classpath (say eclipse), but was missing in production deployments.? 如果文件存在于测试环境的类路径(例如eclipse)中,但生产部署中缺少该文件,会发生什么?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM