Wednesday, October 14, 2009

It's never too late for tests

So you've inherited a pile of buggy, spaghetti code, and now you're supposed to add some new features. We've all been there. It's very easy to say, "The code is already bad, so I'm not going to make the new features any nicer" but you shouldn't. This is your pile of spaghetti now, so you should work to make it incrementally better.

One big step in making bad code better is adding tests (I'm a firm believer in writing the tests first, so you shouldn't have much untested code, but it doesn't always happen). I'm not suggesting you drop everything and add tests to make sure you get to X% code coverage. But, as you add new features, you'll find yourself digging through old code. As you touch different parts of the code, refactor them where needed and add some tests. It will make you more confident in that part of the code, make life easier for yourself, and it will probably uncover some problems that you didn't know existed (and that have probably been there for a long time). A steady approach to testing will make any code better.

Sunday, October 11, 2009

Checked vs Unchecked Exceptions

The debate of whether to use checked or unchecked exceptions are a long debated topic in the Java world, and I'm still not sure that either side has emerged as a clear winner in the eyes of the development community. I personally think that unchecked exceptions are the way to go.

When a checked exception is thrown, there are several typical ways to deal with it.

These methods are the most appropriate ways to deal with a checked exception:

1. Handle it. Do something in response to the exception other than just re-throwing it or logging. If you have an I/O exception, maybe retry the operation.

2. Rethrow it. If you can't handle it, rethrow it, and maybe someone else above you in the call stack can handle it.

3. Wrap it as a runtime exception and rethrow it.

#2 and #3 become a bit more painstaking when methods throw multiple checked exceptions since Java doesn't support multiple exception catch blocks.

There are other ways to deal with it. These are not recommended, but any developer has seen these scenarios:

4. Log it/print stack trace and swallow the exception
5. Do nothing at all and swallow the exception

It's obvious that #4 and #5 can have very bad effects. These exceptions could be indicating some serious problems. While #4 will result in an entry in the log, it still could leave the application in a state that results in some unpredictable behavior. #5 should never be done.

With unchecked exceptions, you have all of the same options. However, #4 and #5 are much less likely since developers frequently do these out of laziness or because their IDE provides this as the default behavior.

Those that favor checked exceptions will say that you are much less likely to handle an unchecked exception since you the compiler does not force a method to declare that it is thrown. While this is true, the same can happen if the method wraps the checked exception in an unchecked one. And, in all actuality, how frequently do you actually handle exceptions vs logging and rethrowing them. If you're like me, you spend much more time doing the latter.

To be fair, there are some times when you really do want to handle the exception. Take the case of the IO exception when you want to retry an operation. Even if it was an unchecked exception, you could use annotations on the method you want to retry (not necessarily the direct method that throws the IO exception), which will work for an unchecked (or checked version) of the IO exception.

public void saveState() {
State state = getState();

private void writeStateToFile(State state) {
// write the state to file

The @RetryOnException idea puts the responsibility on the method that needs to be retried but doesn't require everyone in the call stack to declare an IOException. This idea will work the same for checked or unchecked exceptions.

Tuesday, October 6, 2009

Getting Groovy with XML Parsing

I generally like to use Groovy for data processing, particularly XML parsing. If you've used Groovy before, this won't be anything new, but if you haven't, this example might be enough to make you drink the groovy juice. Given this xml file of an address book, I want to print out all of the people in the address book.


Here's the Java way of doing it (if you've ever done any Java XML parsing, this will look very familiar):

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder parser = factory.newDocumentBuilder();
Document document = parser.parse("xml/sample.xml");
NodeList personNodes = document.getElementsByTagName("person");
List<String> names = new LinkedList<String>();
for (int i = 0; i < personNodes.getLength(); i++) {
String firstName = null;
String lastName = null;
Node personNode = personNodes.item(i);
NodeList children = personNode.getChildNodes();
for (int j = 0; j < children.getLength(); j++) {
Node child = children.item(j);
String nodeName = child.getNodeName();
String nodeValue = child.getTextContent();
if ("firstName".equals(nodeName)) {
firstName = nodeValue;
} else if ("lastName".equals(nodeName)) {
lastName = nodeValue;
names.add(firstName + " " + lastName);
for (String name : names) {

That's 25 lines of Java code to print out a few names (and I didn't even include the public static void main(String[] args) declaration).

Now let's look at the groovy way of doing it:

def addressBook = new XmlSlurper().parse('xml/sample.xml')
addressBook.person.each { p -> println "${p.firstName.text()} ${p.lastName.text()}"}

Just 2 lines, that's it.

Happy groovy-ing.

Friday, October 2, 2009

Java Swing Threading

I've recently spoken with a few developers that were writing Swing apps (some for the first time) but were not familiar with the Swing threading model and the event dispatch thread, so I thought I'd review some of the basics. The main rule of Swing programming is that any code that updates the GUI (this applies only after a component has been realized, meaning its paint method has been called) must be invoked on the event dispatch thread (EDT). This can be accomplished using the methods SwingUtilities.invokeLater and SwingUtilities.invokeAndWait to run tasks on the EDT asynchronously and synchronously respectively. There are some exceptions to the rule, and Sun details those in an article (that whole article is a very good explanation of Swing threading as well).

While this does sound like a straight forward rule, there are some easy ways to get into trouble. One of these ways is when code is updating a GUI's model, which in turn updates the GUI component, that code must be invoked on the EDT. For example, calling model.setDataVector on the DefaultTableModel to update the data in a table must be called from the EDT. Even though you are just updating the model, the model fires an event that updates the GUI (note that some GUI libraries may already handle this for you, but it's not safe to assume this in general).

Violating this rule can cause unpredictable effects. Just like any threading error, reproducing and debugging the problem can be very difficult, so be sure to obey this rule religiously.