Java Reference
In-Depth Information
The Lonely Override
In this code smell, you subclass solely to override a single method. The ThreadLocal class
is a good example of this. ThreadLocal allows us to create a factory that generates at most
one value per thread. This is an easy way of ensuring that a thread-unsafe class can be safely
used in a concurrent environment. For example, if we need to look up an artist from the data-
base but want to do it once per thread, then we might write something like the code in
Example 7-3 .
Example 7-3. Looking up an artist from the database
ThreadLocal < Album > thisAlbum = new
new ThreadLocal < Album > () {
@Override protected
protected Album initialValue () {
return database . lookupCurrentAlbum ();
In Java 8 we can use the factory method withInitial and pass in a Supplier instance that
deals with the creation, as shown in Example 7-4 .
Example 7-4. Using the factory method
ThreadLocal < Album > thisAlbum
= ThreadLocal . withInitial (() -> database . lookupCurrentAlbum ());
There are a few reasons why the second example would be considered preferable to the first.
For a start, any existing instance of Supplier<Album> can be used here without needing to
be repackaged for this specific case, so it encourages reuse and composition.
It's also shorter to write, which is an advantage if and only if all other things are equal. More
important, it's shorter because it's a lot cleaner: when reading the code, the signal-to-noise
ratio is lower. This means you spend more time solving the actual problem at hand and less
time dealing with subclassing boilerplate. It also has the advantage that it's one fewer class
that your JVM has to load.
It's also a lot clearer to anyone who tries to read the code what its intent is. If you try to read
out loud the words in the second example, you can easily hear what it's saying. You defin-
itely can't say this of the first example.
Interestingly, this wasn't an antipattern previously to Java 8—it was the idiomatic way of
writing this code, in the same way that using anonymous inner classes to pass around behavi-
or wasn't an antipattern, just the only way of expressing what you wanted in Java code. As
the language evolves, so do the idioms that you use when programming.
Search WWH ::

Custom Search