Refactoring to Reuse #5

April 17, 2010

#5 – Replace Custom Implementations With Open Source Equivalents

I realize this is a very large category with possibly several dozen examples. In this post, I will highlight this strategy using the Apache Commons IO API. Many applications require the need for accessing file data – reading input business data or even temporary file data is a common need. Typically, you have some class that opens a file, reads data line by line, and either returns a custom java object or a string buffer.

FileReader fr = null;
 BufferedReader reader = null;
 try {
 fr = new FileReader(strFileName);
 reader = new BufferedReader(fr);
 String line = reader.readLine();
 while (line != null) {
 //do something with the line of data...
 line = reader.readLine();
 }
 } catch (IOException e) {
e.printStackTrace();
 } finally {
 try {
 if (reader != null) {
reader.close();
 }
 } catch (IOException e) {
e.printStackTrace();
 }
 }

How many times have you written this kind of logic? :-) When you look to simplify this or want to reduce repetition, consider the Apache Commons IO library. The FileUtils class offers just the method you need for accomplishing the often needed line by line data access to a file. It is trivial to use. For example, see below:

import org.apache.commons.io.FileUtils;
//other lines of code and class declaration omitted...
String strFileName = //path to file...
try {
   File f = new File(strFileName);
   List fileDataLines = FileUtils.readLines(f, "UTF-8");
} catch (IOException ioe) {
 ioe.printStackTrace();
}

That’s it – giving you the same functionality using a far simpler interface. There are several advantages to using these libraries – they are open-source, well documented and tested, and eliminate a lot of redundant code in your application. Travel light and only code stuff that you absolutely must. As I have highlighted before – reuse and agile go hand-in-hand. Less custom code you write, less maintenance for your team.


Follow

Get every new post delivered to your Inbox.

%d bloggers like this: