New Ruby on Rails Tutorial Spring AOP using AspectJ 5
Jan 24

FileParser.eachLine: Learning from other languages

Tech Add comments

At one time, if I had to write some code which was to loop through a file and do something with the contents, I would have thought:

- open the file
- while (there is a line)
- get line
- do something with line
- close up resources

And, I would make sure that all of the IO exceptions are handled correctly, that the resources are closed nicely in a finally { } etc etc.

However, since I get to code in other environments (Ruby, Groovy, etc) I now use a simple utility to do this kind of task. Here is the most simple test case which uses the FileParser utility:

public void testSimpleCommand() {
FileParser.eachLine(sampleFileLineReader, new LineCommand() {
public void useLine(String lineContents) {
assertEquals(sampleFileLine, lineContents);
}
});
}

Now the code that handles file IO is in one place (FileParser) and my application code doesn’t have to worry about it!

Compare this to the Groovy:

new File(inputFile).eachLine { | line | ……. }

Comments are closed.