Flat files in Java made easy: JFileHelpers

June 7, 2008

It’s almost certain every Java programmer out there had to deal with handling of delimited or fixed length flat files at one moment of his career.

I have just created a library that makes it easier to work with that: JFileHelpers. It uses the awesomeness of Java annotations to allow you to handle flat files with minimum changed to existing code. It’s a port of the awesome FileHelpers C# library, by Marcos Meli.

We are also looking for developers who would be interested on joining the team. If you’re not available, you can also help by using the library, and giving feedback on features you’d like to see implemented.

Hope you like it, I would really like to hear your opinions on the library.

Java Closures

April 9, 2007

Click here to read this article in Portuguese.

I quited, long time ago, trying to keep pace with latest tech trends on programming languages. I remember when I started programming, using Clipper, all the news you could get was either by buying a book or a magazine.

Today, when you visit a Digg-like website for programming news, you’ll probably end up finding 3 new and completely revolutionary AJAX toolkits, two articles saying why language x sucks and other three saying it is the best thing since sliced bread, new languages, benchmarks, etc… This scenario obligates you to filter new technology and just investigate whatever you think will be important for your skill set. It’s either that or getting really mad and/or shallow.

Well, some time ago I began to read about Java Closures but never figured out what it was and I really didn’t want to bother about it. Yes, but that was before I found Google Tech Talks, and of more interest, the Advanced Topics on Programming Languages series. I watched a 2-hour talk about Java Closures and finally understood it. Actually it was more than that, I started to like Java Closures.

The principle behind Closures isn’t new. It’s about having code blocks in form of variables. I remember that we had that in Clipper back in 1996. But the new Java Proposal goes beyond, allowing some syntax changes that, in my understanding, makes all the difference. I’ll try to give a brief explanation on what I understood on the topic.

If you ever messed with JDBC or Sockets code, you know there are a lot of boring code to write, something like:

public List getCustomers() {
	List result = new ArrayList();
	Connection conn;
	Statement s;
	ResultSet rs;

	try {
		conn = ConnectionPool.getConnection();
		s = c.createStatement();
		rs = s.executeQuery("SELECT * FROM CUSTOMER");

		while (rs.next()) {
			// ...
		}
	} catch (SQLException e) {
		System.out.println("Error...");
		e.printStackTrace();
	} finally {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
			}
		}
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (SQLException e) {
			}
		}
	}
}

On this code you notice you have 37 lines but business logic is concentrated on lines 7 to 13, or 16% of the code here is business logic. So, when a friend of mine says he doesn’t like Java because it is a bureaucratic language, I have to give in. Imagine having hundrets of data access methods like this on your code. Isn’t it really a lot of duplicated code? Shouldn’t it have a better way of doing this?

Well… Closures to the rescue! 🙂 What if we could write something like:

public List getCustomers() {
	Connection conn;
	Statement s;
	ResultSet rs;

	with(conn, s, rs, { =>
		conn = ConnectionPool.getConnection();
		s = c.createStatement();
		rs = s.executeQuery("SELECT * FROM CUSTOMER");

		if (rs.next()) {
			// ...
		}
	});
}

That’s the new java construct that is being planned to be implemented on JDK7 codename Dolphin. But even better than what we have above, there is an additional construct, called control abstraction syntax. Take a look:

public List getCustomers() {
	Connection conn;
	Statement s;
	ResultSet rs;

	with (conn, s, rs) {
		conn = ConnectionPool.getConnection();
		s = c.createStatement();
		rs = s.executeQuery("SELECT * FROM CUSTOMER");

		if (rs.next()) {
			// ...
		}
	}
}

This snippet of code is translated to the exact same thing as before. This new construct states that a method invocation with a trailing code block is automagically translated into a closure in compile time. Look how elegant and straightforward this method now is. When you read it, you don’t get distracted by a lot of statements that has nothing to do with business logic.

What about the with method? How would it look like?

public void with(Connection c, Statement s, ResultSet rs, { => void } block) {
	try {
		block.invoke();
	} catch (SQLException e) {
		System.out.println("Error...");
		e.printStackTrace();
	} finally {
		if (rs != null) {
			try {
				rs.close();
			} catch (SQLException e) {
			}
		}
		if (s != null) {
			try {
				s.close();
			} catch (SQLException e) {
			}
		}
		if (c != null) {
			try {
				c.close();
			} catch (SQLException e) {
			}
		}
	}
}

The last parameter on that method is the new closure construct. Closures can take parameters and have a return value as well as optionally throw exceptions. Here are some sample closure types:

{int => int}

{int, int => int}

{String => int throws NumberFormatException}

{ => void }

{T => U}

And implementations:

{int x => x+1}

{int x, int y => x+y}

{String x => Integer.parseInt(x)}

{=> System.out.println("Hello world");}

{int, int => int} sum = {int x, int y => x+y}; // sums up x and y

This article is intended to get you started on java closures. For more in-depth understanding watch the first class presentation by Neal Gafter, one of the authors of the closures specification. Here is the link.

Related links:

  • Neal Gafter site about closures
  • Neal Gafter blog
  • Peter Ahé’s Weblog (other author of the specification)
  • James Gosling, about closures
  • Article: Achieving Closures
  • Wikipedia Article on Closures
  • Joshua Bloch on Closures, Resource Management, Google has some good arguments on Closures
  • Change is a good thing – almost always

    October 19, 2006

    Hey there readears,

    I guess it’s been a long time, right? Yeah, lots of things happened since last post, good things indeed. I have quit my previous job to join the Big Blue. Yeah, you know, IBM… I was a little bit skeptic about changing jobs, mostly because I didn’t know exactly what I was going to find here, what kind of project I would be involved on.

    Well, for my surprise the first thing that I received when I started was an excellent trainning on the WebSphere Integration Developer or the WID Tools as IBMers like to call it (yes, they just LOVE letter soups!). And along came the concept of SOA (Services Oriented Architecture), what seems to be the buzzword on the corporate world for the moment. I gotta admit it’s a good concept, but I have been hearing about that for almost 10 years now. SOA mixes WebServices with Workflow tools in a nice way. All you have to do is draw your process and there you go. Well, from a management point of view, that’s kinda true. But behind the scenes, as we all know, there are some hard work. And thanks god there is, imagine if all costumers could build their applications just by pointing and clicking – I would not be hired right now!

    Aside of that, I am involved on a great project, with lots of smart people involved and an excellent team. My manager is reasonable, likes to be involved and the other developers are quite open to hear what you have to say.

    Well, those are the news from the front so far… In minutes I’ll get back to the action with an article about Java and ActiveX interop. See you all by then.

    Cheers!

    Google Code Search: we’re human after all

    October 5, 2006

    Digg!

    Well, I have to confess that sometimes I feel bad for my and for other people’s code. But after searching Google Code, I guess everybody’s normal. Check some fun results, when you:

    Have Fun!!!

    Eclipse, your way

    August 16, 2006

    Recently I found a great website called easyeclipse.org that has many specialized versions of Eclipse. For instance, if you are a Web developer, EasyEclipse Server Java should do the trick for you.

    The catch is that they offer versions with the most useful plug-ins pre-configured into the distribution. In addition, you also can download self-installing plug-ins from the website.

    PROS

    • Out-of-the-box configuration
    • MacOS, Linux and Win32 automated installation
    • Download, click, install plug-ins
    • Multiple languages versions, like LAMP, PHP, Ruby on Rail, Python, …

    CONS

    • Based on rather old 3.1 version

    So, that’s it. Let’s just hope they make the migration to 3.2. When they do I will most likely start to use it as my default IDE.

    See ya next time!

    Update: Cool! EasyEclipse.org’s member Phillip just sent the link to the 3.2 beta preview. Keep up the good job!

    Coding best practices: thinking about it

    August 15, 2006

    Today I have joined a discussion that emerged on our development team: whether to use multiple return statements within the same method.

    Well, back when I was a terrible newbie programmer using Clipper as the main development language, someone convinced me that every function (that was the name for a procedural equivalent of today’s object’s methods) needed one unique return point. I stickied to it but never questioned myself ever again if this is really a good thing to do. Nowadays I got myself doing just the opposite: using multiple return points and when I analyzed it, I found that really better. I’ll explain.

    Imagine the following method that searches for a particular object within an ArrayList:

    private boolean userExists(String name) {
      boolean found = false;
      for (User u : this.getAllUsers()) {
        if (u != null && name.equals(u.getName())) {
          found = true;
          break;
        }
      }
      return found;
    } 

    Doesn’t this method seems a lot cleaner and easier to understand than:

    private boolean userExists(String name) {
      for (User u : this.getAllUsers()) {
        if (u != null && name.equals(u.getName())) {
          return true;
        }
      }
      return false;
    } 

    There are other cases where I can see the code begging for an immediate return 🙂 like:

    private void loadUsers() {
      if (usersLoaded) {
        return;
      }
    
      // do all the lengthy user loading...
      (...)
    }

    In my opinion, the early return when the users are already loaded are easier to interpret and easy to review by another coder than:

    private void loadUsers() {
      if (!usersLoaded) {
        // do all the lengthy user loading...
        (...)
      }
      return;
    }

    I really don’t think it’s a major problem and using one or the other is pretty acceptable but I’d like to hear from you what you think about it so please leave a comment about it if you can. Thanks.

    Update: A friend of mine just e-mailed me an article that addresses the same issue.

    Changing colors of an image in real time

    August 15, 2006

    Recently I needed the ability to change colors of a picture in real-time. I was developing a game where I needed to paint the player costumes many times within the game. I have researched on the internet and didn’t find any J2ME code available.

    I digged all around for an algorithm to do that and found a way to do it.

    Read the rest of this entry »