Showing posts with label Java. Show all posts
Showing posts with label Java. Show all posts

Sunday, September 28, 2008

JavaFX - Applets Part II

SUN entered the RIA foray with its announcement at JavaOne of the JavaFX Rich Client Technology - "a family of products for creating RIAs with immersive media and content across all screens of your life". JavaFX technology includes the following:
  • A runtime plugin similar to Adobe's Flash Player
  • Development SDK including IDE plugins, compiler and debugger
  • A new declarative scripting language for building UIs called JavaFX Script
JavaFX adds a third player in the RIA competitive landscape - the other two being Adobe's Flash/Flex/AIR and Microsoft's Silverlight/WPF. It validates and reinforces the Web 2.5 future we are heading towards - a future where users enjoy applications that are rich, interactive, engaging, cinematic, responsive and stylish, and where developers don't have to struggle with trying to use Web-page-centric DHTML/AJAX technologies to get even very basic, minimally rich applications to work consistently across Browsers and other "screens of your life". Kudos to SUN for recognizing the future and creating a promising, open-source-based RIA solution.

The JavaFX technology for RIAs is conceptually similar to Adobe's Flex and Microsoft's Silverlight in that it has the following key ingredients:
  • A formalized client-side component and event model which is absolutely essential for any RIA with heavy client-side business logic, and which is sorely lacking in the DHTML/AJAX/JavaScript world
  • A JIT-compiled Virtual Machine runtime that is far more efficient than interpreted JavaScript in the Browser
  • A development SDK with editors, designers, debuggers and profilers
  • Built-in support for hardware acceleration and superior vector graphics with a library that supports animations and effects out-of-the-box
The runtime plugin is the Java SE 6 Update 10 runtime. For old-timers that probably brings back bad memories of Applets - the poorest contribution from SUN to the Java world (some would argue that abysmal position belongs to EJB 2.x!). When most people hear Applets they think of massive downloads, install and configuration issues, browser freezes/crashes, Browser back button problems, and ugly UIs. Of course some of the issues are really issues with the Swing technology whose failure caused the emergence of superior technologies such as IBM's (now Eclipse's) SWT. JavaFX is fundamentally a similar Applets technology - in fact the JavaFX site refers to JavaFX programs as Applets (if I were the marketing guy at SUN, I'd call it anything but Applets). However, it looks like there have been some improvements such as:
  • Size of the plugin core needed for typical applications is only a few MB
  • Grahics capabilities look much more refined, competing with Flash and Silverlight UIs
  • Installation, configuration and launch may be easier with the deployment toolkit and JNLP support
  • Runtime performance has been improved
In spite of all of the above, SUN's team would have to work very hard to convince developers that they have a real, commercial-grade solution. The demos at JavaOne kept crashing, but of course that was because of Moscone center's bad network right?! Seriously, early stage demos apart, given the Applets and Swing history, I wouldn't risk real money on this technology until I am fully convinced that it is really more that a fun project for the Computer Science PhDs at SUN. Once bitten, twice shy.

One interesting aspect of this technology is the new language - JavaFX Script. JavaFX Script is a declarative, statically typed language for defining GUIs and application behavior. It provides data binding capabilities for synchronizing UI element state with application data. It is possible to call Java code from JavaFX Script making it easy to leverage existing Java APIs such as the Swing toolkit. It is unclear if we will have something analogous to the Flex-AJAX bridge for JavaFX Script-to-JavaScript communication. With JavaFX Script you can do true multi-threaded applications but I am reminded of Swing developers often shooting themselves in the foot with UI update and the event-dispatch thread. JavaFX Script is compiled to JVM bytecode providing superior execution performance. Some other academically interesting features of the language are described later in this post.

JavaFX Script can be compared to Adobe's MXML/ActionScript and Microsoft's XAML/C#. However, unlike MXML and XAML, JavaFX does not have an XML description of the application UI tree. The UI tree description and the business logic behavior is combined into JavaFX scripts. As a developer looking at Flex and Silverlight to produce commercial software, the first reaction to JavaFX Script is - oh no, another language! Why not just do what Adobe did with ActionScript? - adopt the ECMA Script standard and enhance it where needed. While the ability to work with Java from within JavaFX Script is appealing to Java developers, ActionScript's object oriented-ness and semantics is also quite natural for a Java developer. I wonder if SUN could have served developers better by sticking with the ECMA Script standard which is the basis for ActionScript and JavaScript, and extended it for supporting Java invocation and any other features as needed.

Some other features of the JavaFX technology include:
  • Ability to run an application both in the Browser and on the desktop. In fact you could drag an application out of the Browser and drop it on to your desktop and continue working as a full desktop application. JavaFX applications run in a separate process. Conceivable a JavaFX application crash will not crash the browser - along the same lines of tabs in Google's Chrome Browser running in separate process spaces.
  • JavaFX applications communicate with the server back-end either through Web Services or through RMI. Web Services are extremely useful; but for heavy-duty applications, more efficient mechanisms such as AMF3 over HTTP that Flash/Flex supports is needed (see this). Perhaps someone could implement AMF3 over HTTP support to JavaFX as an open-source project. RMI has issues with firewalls requiring complex HTTP-tunneling solutions.
  • Mobile and TV platform support coming in the future
Coming back to the JavaFX Script language itself, some interesting features that may sound unfamiliar to Java developers include:
  • Classes have attributes (analogous to fields in Java), functions and operations (analogous to methods in Java)
  • The distinction between functions and operations is interesting. One wonders if it adds additional complexity and could have been combined into one construct. Functions are for implementing simple business logic while operations are for complex logic with exception handling. More interestingly, return values of functions are always re-evaluated when the value of any variable referenced by the function changes. This is useful with data binding described below. On a data-binding related note, functions are independent entities that don't need to be associated with a class - this is more of a procedural concept rather than object-oriented one. While the separation of state and behavior is valid on the server for SOA (see this), applying the concept on the client feels weird although it may make sense from a data binding perspective.
  • Function and Operation definitions are outside of the class declaration. The class declaration just contains the declaration of the function/operation. Similarly, attribute initialization is defined outside of the class declaration. This feels more C++-ish rather than Java-ish.
  • Data binding is a useful feature for UI development. An attribute can be defined to be bound to another attribute or to a function so that its value is dynamically (and optionally lazily) updated whenever the bound target value changes.
  • Blocks of code within a "do" or "do later" block execute in a separate thread. While Java developers are familiar with convenient multi-threading mechanisms available in Java, this is the first time a scripting language has provided multi-threading capabilities. While this is a great advantage, it also opens the door for pitfalls for average developers as multi-threading in inherently hard to design and implement correctly for complex applications.
  • Triggers is an exciting feature where you can write code that kicks in on state change events such as an attribute value change. This is not unlike database triggers that developers are familiar with.
  • Attributes can have cardinality operators such as *, ?, + (think regex) to indicate optional, one or more, and zero or more.
  • An attribute can have an inverse declaration indicating a bi-directional relationship with another attribute with automatic update of the inverse on attribute change. This feels like something one does in ORM (Object Relational Mapping) with persistence to a datastore. It seems out of place in a UI development-oriented scripting language.
  • Arrays with "list comprehensions" seem extremely useful. This is like writing SQL statements on lists e.g. var a:Integer* = select n*n from n in [1..10] where (n%2 == 0); New keywords such as insert as first, into, before and after facilitate useful list manipulations.
  • Object literals allow for creating object instances in a JSON-like fashion. While this seems useful, it is likely to lead to very verbose and difficult to read code - see this TableNodeExampleApplet.fx example from a JavaFXpert.
  • Multiple inheritance, which Java avoided due to its inherent complexity, is supported by JavaFX Script.
JavaFX Script is an exciting new language with some cool features that developers have not used in other scripting languages. Obviously some brilliant minds have been applied to its creation. However, my gut feel is that this is a language that, given its many new constructs, is going to have a steep learning curve and a slow adoption.

Overall, the JavaFX technology is very promising and will help usher in the new Web 2.5 era faster. If SUN plays its cards right, JavaFX may catch up with Silverlight and maybe even with Flash/Flex someday.

Sunday, December 30, 2007

Checked versus Unchecked Exceptions in Java


There has always been a debate in the Java community about checked versus unchecked exceptions. Java purists would argue that unchecked exceptions should be used only for conditions you cannot recover from at runtime. On the other hand, in recent years the thinking has shifted a bit (or is it muddled a bit?) with successful frameworks such as Spring promoting heavy use of unchecked exceptions. In the case of lightweight frameworks such as Spring, one of the principal value proposition is the fact that you write very little code to get your job done. Use of unchecked exceptions helps promote that value because you don't need to have try/catch blocks in your code or be forced to declare the exceptions thrown by a method. I believe a significant percentage of software applications are lightweight in nature (see Who produces the most applications software?) with their creators looking for simple, lightweight frameworks such as Spring to get the job done. This is the reason for the widespread adoption and success of such frameworks. For lightweight applications, the use of unchecked exceptions works just fine.

As you move up the chain to more complex applications, the reasoning on exceptions changes. When you have an application with many sub-components written by different groups containing hundreds of thousands of line of code, there is more of a need for rigor and discipline. Building complex software applications is still very difficult and costly. One of the biggest cost in such systems is diagnosing and fixing bugs after the software has been shipped to, and deployed at customer sites. For such systems anything that helps reduce the chances of code problems at development time, or helps diagnose problems after deployment is of immense value. Checked exceptions help towards that goal. Checked exceptions are needed to ensure compile-time detection and enforcement of handling abnormal conditions. Checked exceptions force the developer to think through exception scenarios and code in appropriate exception handlers. These handlers can take appropriate action such as logging state at the time of occurrence of the exception for easy error diagnosis, freeing of any resources for avoiding leaks, applying some corrective business logic such as re-initializing state, or re-casting the exception to fit a service contract. With unchecked exceptions where there is a handler for all exceptions at the top level of the application, all this is not possible.

The natural question that comes to mind is of course - what is considered a complex application and what is considered a lightweight application? Some applications clearly fall in either ends of the complexity spectrum, but many applications fall in a big gray area in between. Complexity also tends to a relative term - complex for one development group may be simple for another. For the majority of such applications in the middle, there is no formula that can be applied to pick the right choice of exception management. The correct approach involves a judicious mix of both checked and unchecked exceptions. I tend to follow the following rules:

  • Use checked exceptions for coarse service contracts to external clients you have no control over. Exceptions are part of the formal service contract you are publishing to your clients.
  • Use checked exceptions for situations that are likely to occur due to invalid input to your services e.g. client called a login service without providing a user id.
  • Use unchecked exceptions within your own service implementation code that performs very basic operations, is exercised very frequently, and where exceptions are unlikely to occur unless there is a very basic flaw in the programming logic. e.g. indexing into a list with an index that is out of bounds. Imagine how painful our code would be if the java.lang.IndexOutOfBoundsException exception of the widely-used java.util.List::get(int) was a checked exception! In fact I use the List analogy and ask myself if the exception scenario is at the same level as the List indexing example. If it is, I use an unchecked exception; if not I use a checked exception.
  • Use unchecked exceptions for conditions from which the program cannot or should not attempt to recover e.g. running out of system memory.