Friday, May 30, 2008

Programming to Interfaces Buy me Something. For sure

Today I've read a post from Ben Northrop - Does Programming to Interfaces Buy Us Anything?

I really understand, that interfaces hurt sometime. And many of us use because of these "reduced coupling, maintainability and testability" features. But there are numerous examples of interfaces usage, which you can dind useful every day:
1) It is very common to switch from JDBC DAO to a Hibernate DAO and conversely, for performance gains, or ad-hoc SQL. Or, from Hibernate to iBATIS, for reporting methods.
2) Though you can generate proxies for classes, they are not easy to test and debug. Let's take a simple ubiquitous example - transactional facade, defined via Spring's interceptor. When you proxy with CGLIB you can end up with stacktrace without source code line information. And you couldn't step through the code, because "source is not found". This can be an IDE limitation, but with interfaces thing are much better.
3) Mock frameworks are not a panacea. Sometimes you need to create mock yourself.
4) Miss F3 in Eclipse for interfaces? Use Ctrl+T!

I can found more practical examples of interface benefits, but they already buy me a lot during my daily work as a developer

Wednesday, May 28, 2008

Beware of hidden autoboxing features

Not so long ago I was asked on some interview - "Can you provide an example of an assignment operation, which causes a Runtime Exception". I started thinking about different casts, but couldn't find such example (though I passed the interview).
I haven't been working closely with Java 5 at those days. I heard and tried all those enums, generics, extended for and so on, but I haven't used this features in a real project.
Now I am involved in such Java 5 project, and recently I was fighting with some obscure exception, which unidentifiable cause and null stacktrace. It looked like this:
InvocationTargetException caused by NullPointerException: null. As all projects now, we are using all those proxies, CGLIB, interceptors etc, but anyway why no stacktrace??
Finally I found the reason. It was an autoboxing usage. The simplest possible example will look like this:

Boolean b = null;
//do something
boolean a = b;

The comparison operator will throw a NullPointerException. Looks very simple, if you already knew this; and if you run a search query "NullPointerException autoboxing" yuo find numerous results. But if you cannot link this NPE with that autoboxing usage, you can spend a day fighting with it, like I did.