views:

106

answers:

2

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. The function writes a string to a log file. It passes its unit test, but fails when one of the Web developers uses it. 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?

+8  A: 

This code relies on the fact that there is a file called debug.log that is writable in the application's executing directory. Most likely the web developer's application is not set up with this file and the method fails when he tries to use it.

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.

Andrew Hare
Yep, I was going to say something about permissions.
Andy White
This makes sense indeed. Thanks for clarifying this!
A: 

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.?

Maddy
Resources (if you mean files, in the context of this question) need not necessarily be pulled form classpath. The program doesn't have to know what classpath is. Classpath is used only by class loader. Java doesn't specify a "working directory" for file IO. It is the responsibility of the programmer to pass a working directory via a command line argument or ideally a system parameter and use it in the program.
Chetan Sastry
That's what I meant by ideally. That would be easy for migration across platform, rather than hardcoding it.
Maddy