Java vs Python

16.12.2006 14:32

Programming.reddit.com atradu labu piemēru iemeslam, kāpēc reizēm ikdienā man nolaižas rokas, paskatoties uz koda daudzumu elementārām lietām.

Here’s the complete Python code for Python 2.5

#!/usr/bin/env python

from __future__ import with_statement

with open('localfile.txt') as f:
    for line in f:
        print line.replace('x','y'),

Note that this script does not leak, in any case, you can’t leave a file open.

Now here’s an equivalent version in Java, with a slight difference: if the BufferedReader constructor throws an exception the file is left open

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

class Replace {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new FileReader("localfile.txt"));
        try {
            String line;
            while ((line = in.readLine()) != null) {
                System.out.println(line.replace('x','y'));
            }
        } finally {
            in.close();
        }
    }
}

And here is, taken from this very thread, the exact equivalent to the Python script (doesn’t handle exceptions, but doesn’t leave files half open):

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

class Replace {
    public static void main(String[] args) throws IOException {
        FileReader reader = new FileReader("localfile.txt");
        try {
            BufferedReader in = new BufferedReader(reader);
            try {
                String line;
                while ((line = in.readLine()) != null) {
                    System.out.println(line.replace('x','y'));
                }
            } finally {
                in.close();
            }
        } finally {
            reader.close();
        }
    }
}

I think we can indeed call this “a ghastly nightmare over the python syntax”, yeah

Komentēt ierakstu: