Thursday, January 15, 2009

Google Programmer Explains Why Static Methods Are Bad For Java Unit Testing

This article made me question my frequent use of static utility methods:

http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/

Here are a couple of the excerpts I liked from the article:

The basic issue with static methods is they are procedural code. I have no idea how to unit-test procedural code. Unit-testing assumes that I can instantiate a piece of my application in isolation. During the instantiation I wire the dependencies with mocks/friendlies which replace the real dependencies. With procedural programing there is nothing to “wire” since there are no objects, the code and data are separate.

Lets do a mental exercise. Suppose your application has nothing but static methods. (Yes, code like that is possible to write, it is called procedural programming.) Now imagine the call graph of that application. If you try to execute a leaf method, you will have no issue setting up its state, and asserting all of the corner cases. The reason is that a leaf method makes no further calls. As you move further away from the leaves and closer to the root main() method it will be harder and harder to set up the state in your test and harder to assert things. Many things will become impossible to assert. Your tests will get progressively larger. Once you reach the main() method you no longer have a unit-test (as your unit is the whole application) you now have a scenario test. Imagine that the application you are trying to test is a word processor. There is not much you can assert from the main method.

The Sunburned Surveyor
Posted on 1:44 PM | Categories:

Best "General" Java Programming Book

I wanted to task some time to mention what I feel is the best "general" Java programming book I've ever read. I'm not talking about a book on a specific Java topic, like Swing or threads, but a book that gives a good overview of the language.

I think the best book of this type is O'Reilly's Learning Java. (I've got the third edition.) The book is written by Patrick Niemeyer and Jonathan Knudsen. Patrick is also the creator of Beanshell, the really cool scripting language that is best buddies with Java (and included in OpenJUMP). The book encourages the use of Beanshell to learn Java.

I wish I would have had this book when I first started to learn Java. I find it still gives me better coverage on some topics than other programming books. For example, Learning Java has a topic on creating classes with generics that is much better than any coverage of the topic in my book that is dedicated to Java generics.

If you are a serious Java programmer, this book should be in your library.

The Sunburned Surveyor
Posted on 12:48 PM | Categories: