Monday, March 27, 2006

Java and Python: A Small Comparison

I have a file called "numbers.txt" that lists the numbers 1-10 on separate lines. I want to make a small program that reads all of the lines and prints the numbers to stdout in the following format:
1 2 3 4 5 6 7 8 9 10

Here's the somewhat minimalistic Java code to do this:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class Numbers
{
public static void main(String[] args)
{
try {
BufferedReader br = new BufferedReader(new FileReader("numbers.txt"));
StringBuilder sb = new StringBuilder();
String str;
while( (str = br.readLine()) != null) {
sb.append(str.trim() + " ");
}
sb = sb.delete(sb.length() - 1, sb.length());
System.out.println(sb.toString());
br.close();
} catch(IOException ioe) {
ioe.printStackTrace();
}
}
}



Now compare that code with Python code that does the exact same thing:

if __name__ == "__main__":
try:
sock = open("numbers.txt", "r")
print " ".join([l.strip() for l in sock.readlines()])
sock.close()
except:
print "Error reading from numbers.txt."



Several things jump out at me here:
1. The Python code is much more expressive.
2. The Python code is much closer to the way I think.
3. The Python code doesn't make me deal with nearly as many mundane, niggling details. For example, Python doesn't force me into an object-oriented paradigm (even though I could go there if I wanted to).
4. The Python code to me 30 seconds to write. I needed roughly 3-4 minutes to produce the equivalent Java code, because I had to look up appropriate method calls in StringBuilder and BufferedReader. In addition, I had one compilation error with javac (I had originally named my file "numbers.java" instead of "Numbers.java").

Obviously, the example described here is somewhat contrived; nevertheless, it illustrates some of the reasons why I like programming in Python and why I loathe programming in Java.

0 Comments:

Post a Comment

<< Home