Effective Java

Effective Java, Joshua Bloch, 2008Book Review: Effective Java
2nd Edition, June 2008
by Joshua Bloch
Addison Wesley, 346 pages
ISBN: 978-0-321-35668-0



This book seems to be one of the most critically acclaimed Java titles. What could I possibly add to what has been said? The acclaim is fully deserved. I had the feeling that I already learned something new and important as soon as I reached page twenty. This is something that I cannot say of very many books. Effective Java manages to be extremely useful and simultaneously extremely easy to read.

However, “easy” doesn’t mean simple in this case, since many of the discussed problems are subtly complex. Some are so complex, in fact, that Java beginners might not fully understand or appreciate them. So, it’s probably not a book for beginners. On the other hand, the book is neither esoteric. The 78 items are general Java programming issues which one is likely to encounter in everyday work at some point, regardless of any specific domain.

The book is written in a clear and concise language and each problem is exceptionally well reasoned. The author has a very deep understanding of the Java language, which is rather apparent and no surprise, since Joshua Bloch is one of the architects of the Java platform. Incidentally, this also means that the problems are discussed from the perspective of an API designer rather than from the perspective of an application programmer.

This is useful, because it is primarily concerned with creating robust and high quality interfaces. Architects, designers, and application programmers benefit likewise from this. The items discussed in this book can probably be described as design and implementation level rationales. They are grouped by Java categories, such as generics, enums, annotations, exceptions, serialisation, as well as by more general concepts, such as  object creation, classes and interfaces, methods and concurrency. Many of the individual topics are related; therefore the author makes ample use of cross references, which is helpful for reference use.

The included code examples are a joy to read; they are clear, concise, and always illustrative. While discussing the intricacies of the above named topics, Joshua Bloch casually introduces the reader to a good number of commonly used design patterns, many of which are illustrated with code examples. However, design patterns are not themselves formally discussed.

The book equips Java programmers with an arsenal of relevant best practices, from comparatively simple things such as creating objects, implementing “equals()” and “hashCode()” methods to more advanced topics, such as concurrency, mutability, and thread safety. In doing so, Joshua Bloch points out quite a few quirks and peculiarities of the Java language, and he does not only point them out, but explains their practical consequences in detail. Thus, the book has great didactic value, as the reader will end up with a higher level of familiarity with the language. Reading this book is time well invested for any Java programmer.

Too much Java

You know you had too much Java…

…when you type a company memo and begin with the heading “public static final”.
…when you drop your used paper cups on the floor stating that the garbage collector will take care of it.
…when most of your email attachments are jar files.
…when you feel lost without an application server.
…when you refer to your wife as domestic domain expert.
…when you say “use case actor” instead of “user”.
…when you attempt to subclass meeting agendas.
…when you write down your shopping list in string array notation.
…when you think that the “Java community process” has nothing to do with Indonesian politics.
…when you begin all your annotations with an “@” sign.
…when you can type “System.out.println” in less than 2 seconds.

Java Currency Conversion Class

Commercial applications that aim to provide multi-currency functionality need a currency converter facility with access to up-to-date foreign exchange rates. This is what the CurrencyConverter class offers. Click here to download the CurrencyConverter.java source code.

static CurrencyConverter getInstance()
  Returns a singleton instance of CurrencyConverter.
double convert(double amount, java.lang.String fromCurrency,
java.lang.String toCurrency)
  Converts a double precision floating point value from one
  currency to another.

long convert(long amount, java.lang.String fromCurrency,
java.lang.String toCurrency)
  Converts a long value from one currency to another.

boolean isAvailable(java.lang.String currency)
  Check whether the exchange rate for a given currency is available.

java.lang.String[] getCurrencies()
  Returns all currencies for which exchange rates are available.

java.util.Date getReferenceDate()
  Get the reference date for the exchange rates as a Java Date.

java.lang.String getCacheFileName()
  Get the name of the fully qualified path name of the
  XML cache file.

void setCacheFileName(java.lang.String cacheFileName)
  Set the location where the XML cache file should be stored.

void clearCache()
  Delete XML cache file and reset internal data structure.

The CurrencyConverter class provides an API for accessing the European Central Bank's (ECB) foreign exchange rates. The published ECB rates contain exchange rates for approx. 35 of the world's major currencies. They are updated daily at 14:15 CET. These rates use EUR as reference currency and are specified with a precision of 1/10000 of the currency unit (one hundredth cent). The convert() method performs currency conversions using either double values or 64-bit long integer values. Long values are preferred in order to avoid problems associated with floating point arithmetics. A local cache file is used for storing exchange rates to reduce network latency. The cache file is updated automatically when new exchange rates become available. It is created/updated the first time a call to convert() is made. By calling the clearCache() method before convert(), a reload of the exchange rates from the ECB server is forced. The CurrencyConverter class is implemented as a simple singleton; it is currently not thread-safe. It should be fairly easy to change it into a Java Bean, or to add code for sub-classing. Update Oct-2009: Manish Dubey has extended the CurrencyConverter class to access exchange rates up to 90 days in the past. With this extension, exchange rates for any currency can be retrieved with a specified date within the last 90 days. You can download the extended version here.

RAD with Java

When you think of Java, you probably think of object-oriented programming, virtual machines, and enterprise development. Most likely you won’t think of rapid application development (RAD). Traditionally, the term RAD is associated with “entry level” development tools, such as Visual Basic, whereas Java is associated with “serious programming”. This is the conventional view, but one may ask whether this view is still valid. During the past few years, RAD programming tools have matured while professional high-end tools have become easier to use. The development environment dubbed “Java Studio Creator” from Sun Microsystems is a case in point.

The Java Studio Creator (JSC) is an integrated development environment (IDE) for building web applications based on the Java Server Pages (JSP) and Java Server Faces (JSF) technologies. The IDE resembles Visual Studio 2005 and this similarity is probably no coincidence. Sun wants to attract cross-over and entry level developers to the Java world with this product. When looking at the opening screen, Visual Studio developers will feel right at home. The IDE is built on top of Netbeans, Sun’s own IDE and development platform. It offers a streamlined environment for the development of production-quality Java web applications and portlets (pluggable web-based user interface components). Applications can be built easily by drawing user interface pages in a visual editor, filling in the Java code for event handlers, and connecting the navigation elements on different pages. The IDE can be downloaded at no cost at http://developers.sun.com/jscreator/downloads/.

It seems that Java just doesn’t get easier. Creating a simple application with two or three pages containing master/slave tables, search, and create/read/update/delete (CRUD) functionality only takes a few hours. The work process is very similar to creating a desktop application with a visual GUI builder, such as Delphi, Visual Basic, or Sun’s own Matisse. Data-aware components can be bound to database columns, Java bean properties, or EJBs. The level of productivity is comparable to the mentioned RAD tools. It comes close to, or even surpasses the productivity of popular dynamically typed web development languages. Java Studio Creator automatically generates JSP and Java skeleton code. It offers SOA and Web Services integration, Ajax components, and single-click build and deployment. JSC comes bundled with Apache Derby and Sun’s own application server. It supports third-party application servers, as well as any database with a JDBC driver.

The JSC user interface is designed with high-resolution monitors in mind. The main window in the middle can be switched between WYSIWYG visual editing and JSP/Java cod editing. Changes in the visual editor are immediately reflected in the code editors and vice versa. The palette window in the upper left corner contains JSF components that can be dropped into the visual editor. The server window provides access to server resources, such as EJBs, web services, data sources, and databases. The outline view in the lower left corner presents a hierarchical view of the application objects, whereas the navigation view shows the members of the active Java class. The property editor in the upper right corner allows customisation of components in Delphi/VB style. The project and file windows in the lower right corner display the hierarchical structure of the “physical” parts of the application, such as directories, files, beans, packages, libraries, etc. Finally, the refactoring and output windows show program output and the results of code refactoring operations.

Thanks to the excellent tutorials available from Sun at http://developers.sun.com/jscreator/learning/tutorials/2/index.jsp, it took me only a few late night sessions to get acquainted with the IDE. Within a week I was able to create a database-driven multi-page web application with form verification, EJB access, and an attractive Ajax user interface. I reckon that this could even be done by a developer who is not familiar with JSP and JSF, because these technologies are hidden away by the IDE and require no coding effort. The only requirement is some familiarity with the Java language. Hence, JSC may be interesting not only for Visual Studio enthusiasts, but also for experienced Java programmers who are new to web programming. Its learning curve is considerably flatter than those of traditional Java web frameworks, such as Struts, Tapestry & Co. The Java Studio Creator’s current version is “2 Update 1”. This may also be its last version, because the JSC product is now in the process of fusing with the mainstream Netbeans IDE. The current Netbeans version (http://www.netbeans.org) installed together with the Visual Web Pack offers an almost identical functionality and look.

Java SE 6 is available

After more than two years development time, Sun has announced the release of the Java Platform Standard Edition 6 (Java SE 6, code-named “Mustang”) this month. The runtime environment (JRE6), the development kit (JDK6), documentation and source code can be downloaded directly from Sun at this URL: http://java.sun.com/javase/downloads/index.jsp. Simultaneously, Sun has released a new version of its free Java IDE, Netbeans 5.5, with full support for Java SE 6.

Sun is also moving one step closer to making Java open source. Parts of the new Java version were already released under the GNU General Public License in November. The comprehensive Java class library, which constitutes the largest part of the Java platform, will be released under the GPL in the first quarter of 2007. This move will then complete the open-sourcing of Java. In spite of Java becoming open source, the platform and its future development will still be overseen by the JCP Executive Committee, which steers the Java Community Process established in 1998.

One of the most important innovations of Java SE 6 is scripting language integration, which makes it possible to mix dynamically typed scripting languages, such as JavaScript, PHP, Python, or Ruby with Java code. While add-on packages for diverse scripting languages have been available for some time, Java now provides built-in support via a standard interface that conforms to the JSR-223 specification. This provides a standard mechanism to execute scripting languages from within Java and it allows those languages to access Java classes and resources.

Furthermore, Java SE 6 comes with greatly enhanced support for XML web service client applications covering the current specifications for JAX-WS 2.0, JAXB 2.0, STAX and JAXP. It includes new parsing classes and XML to Java object-mapping APIs, which were previously only available in Java EE platform implementations or the Java Web Services Pack. The XML Digital Signatures API allows programmers to secure Java-based Web services by performing cryptographic operations on XML data. The Java-XML Web Service (JAX-WS) 2.0 API updates the library formerly named JAX-RPC. Improvements to Java-XML Binding (JAXB) 2.0 include XML schema support and class binding to a schema. Lastly, the Streaming API for XML (STaX) provides a bi-directional API to read and write XML via a stream of events, including the ability to skip sections, and focus on sub-sections of documents.

A notable new feature primarily aimed at system and tool developers is the new compiler API that allows compiler access from Java programs. With this new API it is possible to compile source code from within a Java application. While this is not a feature used by the typical application developer, it will be a welcome improvement for code-generating frameworks, such as JSP or PHP, simplifying the interactive process of creating code.

Java SE 6 incorporates many important improvements for the development of GUI desktop applications, in particular by giving Java applications access to features available on the native OS desktop on basis of JDesktop Integration Components (JDIC). This includes, for example, support for splash screens, tool tips, pop-up menus, icons, and system tray, support for native file extensions, and integration of client browser and email applications. Numerous enhancements were made to JFC, Java2D, and Swing, such as a new Windows API, improved drag-and-drop operations, true double buffering for smooth graphic transitions, just to name a few. A new layout manager component based on the NetBeans Graphical Interface Builder (previously named “Matisse”) offers a visual development environment which makes it possible to “paint” graphical user interfaces.

Other new features in Java SE 6 include new monitoring and management tools providing more diagnostic information, JDBC 4.0 with out-of-the-box Java DB, pluggable annotations, and new security APIs.