Effective Java Reloaded – This Time It’s for Real

Joshua Bloch presented on his upcoming book Effective Java Reloaded. This was a repeat of his presentation given during last years JavaOne. I was astounded on the line to get into the room for this presentation. The line snaked the pavilion and back.

The following are some the suggestions given by Joshua during the Effective Java Reloaded session.

For object creation, Joshua recommends using the static factory pattern. The static factory has advantages over constructors, such as allowing flexibility for returning subtypes, caching, and in Java 5 you can do type inference.

Use the builder pattern to overcome the numerous telescoping constructor signatures or the bean style getter/setter methods. The build() method of the builder class constructs a object in a consistent state and can check for inconsistencies.

The following tips deal with Java generics.

Joshua suggested to avoid raw type in new code. Use generics for compile time checking. He recommends that you fully understand each warnings caused by generics and try to eliminate them if possible. If you can’t eliminate the warnings, suppress them at the lowest possible scope using the @SuppressWarnings annotation.

Use bounded wildcards to increase applicability of APIs. Use <? extends T> when parameterized instance is a T producer. <? super T> when the API is a T consumer.

Don’t confuse bounded wildcards with bounded type variables. A bounded type variable, <T extends Number>, restricts the actual class to a subclass of the typed parameter, in this case Number.

As a rule of thumb, if a type variable appears only once in a method signature, use wildcard instead. It is usually best to avoid bounded wildcards in return types. Don’t overuse wildcards, it might water down the benefits of generics.

Generics do not mix well with arrays or variable length arguments. If given a choice, choose generics.

Joshua also talked about a cool mind expanding pattern, the Typesafe Heterogeneous Container (THC) pattern, which he talked about last year.

Joshua said that generics are tricky but well worth learning as they make your code better and safe.

Joshua also recommended the use of the @Override annotation every time you want and think you are overriding a method because sometimes you are overloading a method instead.

And finally, final is the new private. Minimize mutability where ever possible, but be caution when working with serialization or cloneable.

Technorati Tags: , , , ,


Leave a Reply