‏إظهار الرسائل ذات التسميات java. إظهار كافة الرسائل
‏إظهار الرسائل ذات التسميات java. إظهار كافة الرسائل

السبت، 2 أكتوبر 2010

Finally! JavaFX script is dead

I never fully understood JavaFX script. It seemed like a nice enough language, but it neither completely replaced Java nor integrated well with it. Furthermore, some of the features of its library were sorely missing from Java, but not accessible from it. This is why it is refreshing to see the new JavaFX Roadmap. Its main tenet is that JavaFX script is being discontinued and that JavaFX becomes a framework for Java with many exciting features:

  • Binding API: Well, OK, yet another one. Here is hoping that it will not be too cumbersome and find broad acceptance. The API will include observable collections (which are handy for GUI lists and tables).

  • Media framework: for audio and video. About time.

  • HTML5 support: parsing and display. Also desperately needed in Swing (SWT already has reasonable HTML display support).

  • New table control: Apart from better looks, combining it with observable collections should get one the comfort offered by Glazed Lists.

  • New rich text control.

Finally Java gets back the human resources that had been moved to JavaFX script by Sun. The new JavaFX features will make it much more appealing for developing desktop applications.



Update 2010-12-15: Why the new JavaFX makes sense

الأحد، 1 أغسطس 2010

Why we are actually writing getters and setters in Java

I now often hear the opinion that writing getters and setters has something to do with better encapsulation, that using “naked” fields is bad practice. To find out if this is true, we have to look at Java history. In the mid-nineties, Sun developed the Java Bean Specification as a component model for Java. This model was supposed to help with tool support for Java, e.g. when connecting a graphical user interface with domain objects. In this case, it is useful if one can observe changes made to fields and react to them (e.g. by updating the text displayed in a window). Alas, while there are some languages that allow this kind of meta-control (Python and Common Lisp come to mind), Java does not. Thus, Java Beans introduced standardized naming that allowed one to implement a field as a pair of methods which then would manually implement the observation.



I usually code as follows: If I need just a field, I use a public field (no getters and setters), because it helps me to get started quickly and introduces less clutter. If I later change my mind, I let Eclipse introduce the indirection of the getter and setter. That means that there is no penalty for such a change and no need to think ahead! Granted, having both public fields and getters/setters affects uniformity, but the added agility is worth it for me.



Obviously, it would be nice if Java had true observable (and optionally computable) fields. This feature was initially on the table for Java 7, but did not make the cut. Maybe IDEs could help by displaying getters and setters as if they were fields. Their source code would be hidden, with visual clues indicating if such a pseudo-field is read-only etc. Additionally, auto-expansion would be improved, because pseudo-getters (such as Collection.size()), getters/setters, and fields would all be part of the same category. No more typing “.get” and hoping that the information that you are looking for is available as a properly named getter. The same kind of grouping should also be made in JavaDoc. Lastly, one could display foo.setValue("abc") as foo.value = "abc". But I’m not sure if that makes sense.



Addendum (2010-08-07): I think I did not make my point clear. It was not “use public fields”, it was “don’t use getters and setters blindly”. I’m applying the coding style mentioned above during an exploratory phase of coding. IDEs such as Eclipse allow you to do this kind of quick and dirty exploration because real getters and setters are always just a refactoring away. I do agree that, as soon as the API and its client code are not in the same code base, you cannot do these refactorings, any more. Thus, you have to think ahead and freeze some things.



As for generating getters and setters: Yes, Eclipse does that for you. It even expands getFoo into foo getter source code and setFoo into foo setter source code. And it can also rename the setters and getters for you while renaming a field. Even then, getters and setters still add clutter.

الأحد، 11 يوليو 2010

Use a single version number for Ant and Java (bonus: GWT)

Problem: If your application has a version number, it should be accessible during run time from Java (e.g., to display it in an “About this application” dialog) and during build time from Ant (e.g. to include it in file names). The solution is as follows.

Access the version from Java

Create the following properties file src/de/hypergraphs/hyena/core/client/bundle/BuildConstants.properties and put it into the class path.

buildVersion=0.2.0

Access BuildConstants.properties as a Java resource. I usually construct the resource path relative to a Java class (a sibling of the file). That way the path to the properties file will always stay up-to-date, as long as I move the Java class with it.

Ant

Ant can read external property files as variable with the following statement.
    <property file="src/de/hypergraphs/hyena/core/client/bundle/BuildConstants.properties">

Additionally, you can insert the value of $buildVersion into a file while copying it, by using a filterset.
    <copy file="${data.dir}/index.html" todir="${version.dir}">
<filterset>
<!-- Replace @VERSION@ with the version -->
<filter token="VERSION" value="${buildVersion}">
</filterset>
</copy>

GWT

For client-side GWT, you can use constants. Then the version number is compiled directly into the JavaScript code. To do so, you add the following interface as a sibling of BuildConstants.properties.
package de.hypergraphs.hyena.core.client.bundle;

import com.google.gwt.i18n.client.Constants;

public interface BuildConstants extends Constants {
String buildVersion();
}

الأحد، 2 مايو 2010

Running a WAR as a desktop application

If you have written a web application, the next logical step is to make it available offline. The long-term solution is clear: You give your web application an offline mode, which will hopefully be complemented by explicit application management in web browsers. Short- to mid-term, though, that is often not feasible, because the server provides crucial functionality to the client. Thus, I was looking for a different solution.



One option I had seen was Hudson’s self-executable WAR file: When you execute java -jar hudson.war, an embedded web server starts and you can immediately try out Hudson. This approach had two limitations that I didn’t like. First, I wanted my solution to be acceptable for end users, so I wanted a graphical user interface. Second, the embedded web server extracted the WAR file to a temporary directory and did so again for each startup, wasting time. In contrast, my solution does the following things:


  • The application is a JAR file, the WAR is embedded inside. I opted against a single binary for JAR and WAR, because packaging the JAR as a nice desktop application adds platform-specific data, anyway, and makes it often impossible to deploy the result as a WAR.

  • When the JAR starts up, a Swing user interface is shown. If this hasn’t been done before, the WAR file is extracted to a directory next to the JAR file. The idea is that there is a dedicated folder for the application in which the JAR resides. The location of the JAR is determined via this trick. The WAR file (=ZIP format) in the classpath is extracted to the file system using the standard Java API.

  • Next, a web server is started and pointed to the web application directory in the file system (none of the web servers I’ve seen is able to serve a WAR file directly, let alone one that is embedded inside a JAR file). I used Winstone, because it is so small. There are even smaller ones, but those won’t allow you to use servlets. Obviously, any embeddable Java servlet container will do.


  • A button allows the user to open the starting page of the web application in the default web browser. java.awt.Desktop (Java 6) allows you to do this. Currently, localhost and a fixed port is used. In the future, the port should be configurable and one could maybe automatically switch to a different port if the default one is occupied.

  • Finally, I also produced a Mac OS X application. Such an application is a folder with the file name extension “.app” and the JAR file inside. This has the nice side effect of hiding the extracted WAR directory.



This is all there is to it. Now even non-technical end users can try out my web application without having to go through the steps of downloading and installing a web server. You can download the Eclipse project of my implementation (be warned, the code is quite experimental).



الخميس، 29 أبريل 2010

Finding out where your class files are

Sometimes, when you are writing a program, you need to install data (e.g. by unzipping example files) or to find additional data (e.g. plugins). If you know the location of your class files, you can put the data close to them or start your search there. Your program will usually be packaged as a JAR file, so this scheme allows you to keep everything in the same directory. But any solution should also work for unarchived files, because you want to test while developing your (un-jarred) code. Until now, I’ve always used hacks involving Class.getResource() and looking for exclamation marks in the returned URL to find out if the program is currently running from a JAR. Recently, I’ve discovered a simpler solution (source):

ProtectionDomain protectionDomain = HyenaDesk.class.getProtectionDomain();

File codeLoc = new File(protectionDomain.getCodeSource().getLocation().getFile());
For example, this code computes the following two values for codeLoc.

  • Unarchived: /home/rauschma/workspace/hyena_desk/bin

  • JAR: /home/rauschma/workspace/hyena_desk/build/hyena_desk.jar


الجمعة، 2 أبريل 2010

GWT, an important Java technology: features, future and wishes

The Google Web Toolkit (GWT) has become one of the most important Java technologies, as it gives that language a credible web platform strategy. I used to be doubtful of the extra compilation step and developed with DWR and Dojo, but have since become a convert.

Cool features:
  • A single code base for client and server.
  • Great development tools, via Eclipse: refactoring, code navigation, etc. This was one of the reasons the creators of GWT chose Java as the source language. Server-side JavaScript certainly would have been a possibility, and compiling JavaScript to JavaScript is not unheard of, either.
  • Quick turn-around: after making changes, the server and client can be reloaded quickly to reflect those changes (only the first start of the client is a bit slow, subsequent reloads are fast).
  • Easy install of development tools: All you need are two Eclipse plugins and you are done.
  • IDE support: One of the Eclipse plugins helps with various coding tasks and errors (such as keeping Service and AsyncService consistent).
  • Easy deployment of applications: GWT produces a WAR file. Drop it into a servlet container such as Jetty or Tomcat. Done.
  • Fast and reliable GUI layout: Still limited compared to what Swing and SWT offer, but for the first time acceptable.
  • True client-side technology: GWT is tightly integrated into the browser environment and stays close to JavaScript. This makes it easy to keep pace with the rapid progress that browsers are making. GWT is also one of the few Java frameworks that can be used to write offline web applications, because it relies so little on the server.
Extending the basic features: For someone who has already programmed Swing or SWT, it is very easy to get started with GWT. After a while, you will probably be looking for advanced features. Luckily, a lively community has grown around GWT to fulfill this kind of need.
  • gwt-dnd: Implements Drag and Drop in pure GWT.
  • Smart GWT: GWT does currently not have too many widgets. Smart GWT is a GWT wrapper around the SmartClient JavaScript library which has lots of widgets. While GWT is really good at this kind of wrapping, there is some baggage involved: load times of web applications increase, and there is a new API to learn.
  • GWT Mosaic: Also extends GWT, but as pure GWT and with less widgets/features.
  • Other wrappers for JavaScript libraries exist. But beware, some of them have very restrictive licenses.
What the future will bring:
  • Currently, the GWT incubator hosts experimental features. Long-term, its parts will be migrated to either separate projects or the GWT core.
  • A post reveals interesting things about GWT’s future. For example, it will get data-backed widgets.
What I am missing:
  • More widgets: The current widgets are limited (menus don’t ensure that they are visible, no support for shortcuts, no resizable dialogs, no context menus, etc.) and there are not enough of them. I expect this area to improve quickly, though, now that all the important foundations have been laid (event handlers, modular CSS, layout panels).
  • Switching back-ends: Many computers are only intermittently online. Programming an offline mode for a GWT application is difficult, because the server usually hosts important functionality. A hypothetical way of solving this is by installing a back-end locally. The client could switch between this back-end and the server. Managing installed back-ends should work similar to Java Web Start. A local back-end could also provide a GWT application with desktop features, because it has access to desktop resources such as the file system.
  • Better client-side modularity: I love Eclipse’s modularity, especially when working in a team. You can have a core plugin that is extended via other plugins residing in separate projects. It would be nice if one could extend a GWT application in a similar fashion. On the server side that is possible via OSGi. On the client side, that is currently not possible.
  • Sending binary data from server to browser: For example, one cannot create images on the server and send them to the client via RPC. Data URIs are a work-around, but a poor one.
  • Annotations for hiding code from the client: If an object is transferred back and forth between client and server, there are often some server-only methods. An annotation would allow one to hide those methods. There is an issue for this feature. You can star it, if you would like to see it fixed.
  • Instantiating classes via class literals: There is no Class.newInstance() in client-side GWT. One has to resort to sending a factory to the client.
  • Two two useful methods: Class#getSimpleName(), String.format() are simple to implement, so I don’t see the reason for not doing so in client-side GWT.
  • Simpler unscrambling of GWT method names: If you want to invoke GWT code from JavaScript you need to prevent GWT from scrambling your method names. Doing this is a bit more complicated than it should be. A simpler solution would be to add an annotation to methods whose names one wants to preserve.

الجمعة، 12 مارس 2010

File system storage and servlets

One of the blessings of the JVM is that there are many “pure” databases available for it; Sesame (RDF) and Apache Derby (relational) come to mind. Alas, these databases need to save their files somewhere. This becomes a challenge with Servlets: Where should one put these files? Pre-packaged, read-only, files usually reside in SERVER/webapps/app/WEB-INF/, but mutable files? Putting them in WEB-INF makes upgrading a web application more difficult. I can easily imagine myself accidentally removing such data during an upgrade. The best solution, that I was able to come up with, is:

  • By default, the data directory of a web application “app” is SERVER/webapps/app.data/WEB-INF/ (WEB-INF is necessary to protect against serving secret files).

  • This can optionally be configured via a file SERVER/webapps/app.properties. There, one can specify the servlet data directory via a relative or an absolute path. The former case is useful if you want this directory to be a sibling of SERVER/webapps. The latter case is useful for putting this directory anywhere on a system.

I do realize that there are security issues with this scheme: While it worked for me on Tomcat, I would expect other servlet containers to prevent servlets from writing files in this manner. Other options are:

  • Make the data directory a servlet parameter in web.xml: Complicates upgrades.

  • Specify a directory via the Java preference API: Prevents installing the same web application multiple times on the same system.

  • Storing the data in a temporary (as in File.createTempFile()) directory: Not a solution for long-term persistence.


Are there other solutions out there? Let us know in the comments.



Update 2010-12-14: One of the comments already mentioned this solution: I finally opted for storing files in the home directory. In Windows, the home directory is rarely directly accessed, while under Unix you can hide your web-application-specific directory by prefixing its name with a dot. So this solution works out well in both cases and fulfills all of the above requirements.

الأحد، 28 فبراير 2010

Is it time for a JVM-based web browser?

Figure 1: Screen shot of JWebPane in action (source).



There are currently two exciting platforms for which one can develop:

  • The Java Virtual Machine (JVM). Advantages: Great tools, hosts many languages, lots of free software is available for it (databases, support for many file formats, etc.), supports modularity (OSGi, Jigsaw).

  • The web browser. Advantages: One can quickly try out an application without downloading anything, URLs encode application states and are bookmarkable, the ability to clone application states via tabs, integrates hypermedia and data streams of all kinds.


Then how about combining these two platforms? It seems like a missed opportunity for the JVM that all major browsers now have JITs for JavaScript, but none of them uses the JVM. What would a JVM-based web browser look like?

It would be modular, every aspect of it would be extensible in Java. It would be host to a new kind of web/desktop application hybrid. If the JWebPane technique of porting Webkit to Java2D really works, then it can even provide a perfect web experience (Fig 1, 2). Alas, it has been a long while since there was any news about JWebPane.



Figure 2: JWebPane is a port of Webkit to the JVM (source).


I do realize that applets go a long way in the direction of this vision, but several minor details add up so that one still feels the barrier between Java and the browser. I could never get excited about JavaFX, it always felt like Java was trying to be like Flash. But the idea of a JVM-based web browser, HotJava 2 if you will, does excite me in ways I cannot all explain rationally. I can see myself extending such a browser with many tools and writing all my future applications based on it.



Update 2010-03-02: See my comment below on a refinement of these ideas.

Update 2010-12-15: Oracle has granted my wish and turned JavaFX from a language into a library.

الأحد، 22 نوفمبر 2009

Things I miss most in Java

The following is a list of the language features I miss most when programming Java:



  • Closures: are useful for implementing abstractions that involve behavior. Smalltalk provides ample proof that functions and object-orientation go together well. Instead of giving Java functions as objects, its creators decided to support the encapsulation of behavior via inner classes. At long last, it looks like Java 7 will have closures. They are essentially functions with built-in compatibility with single-method interfaces. Not perfect, but certainly very useful.

  • Modules: are also coming to Java 7. Reinier Zwitserloot has a nice write-up of the rationale and current state of Jigsaw, Java’s module system. It is interesting that one requirement was that module have to cross-cut packages so that the core of Java can be properly modularized.

  • Generators: let one repeatedly invoke a method. The method does not return a value, it yields it. A yielded value is passed to the caller in the same manner as with a return statement. But, the next time the method is invoked, execution continues after the last yield. Thus, a yield suspends method execution, and an invocation resumes it. This helps whenever data has to be computed lazily, on demand and in a piecemeal fashion: (The beginning of) an infinite list can be iterated over by writing a generator with an infinite loop. Tree iterators become trivial to write; one uses a generator and recursion. And so on... Astonishingly, generators are already in an experimental version of the JVM.

  • Mix-ins: are class fragments that can be added to (mixed in) any given class, while defining it. The effect is similar to multiple inheritance, but results in a chain of classes (and not a tree, as with true multiple inheritance). Mix-ins are also sometimes called abstract subclasses, because they are classes whose superclass is left to be filled in. While it doesn’t look like mix-ins will be added to Java anytime soon, they could be simulated by tools as interfaces with implementations: If one attaches method implementations to special mix-in interfaces, those implementations could be automatically added to classes implementing such interfaces. While the compiled code will contain redundancies, the source code won’t and subtyping will work as expected. The attaching could be done by letting an annotation refer to a class.

  • Post-hoc interfaces: Wouldn’t it be nice if one could let a class implement an interface after it has already been defined? After all, one can add new leaves to the inheritance tree, why not new inner nodes? This would give one many of the benefits of duck typing, while keeping compile-time checking.


While other features (such as multiple dispatch and better code browsing) would be nice to have, the above list contains my most urgent wishes for Java.

الخميس، 19 نوفمبر 2009

Java 7 will have closures!

These pages have the details:
  • Closures after all?” is continually updated with new links and information.
  • Gafter’s “Closures for Java” has been updated with the new syntax which closely resembles FCM. Thus, the new closures use FCM syntax and (a simplified version of) Gafter’s type system. Correction: Gafter’s spec was written 2 weeks before Devoxx, as an attempt at a compromise between the competing proposals.
  • Reinier Zwitserloot has more background on how everything came about.
  • Update 2009-11-22: Stephen Colebourne gives an overview of the current situation.
  • Update 2009-12-03: Mark Reinhold posts “Closures for Java: The Q&A”.

الاثنين، 24 أغسطس 2009

32bit Java 6 on Mac OS X Snow Leopard

This is great news and confirms my prior suspicions. Finally, one can safely target Java 6 on the Mac, as I expect PPC Macs to become slowly irrelevant and most users to upgrade to Snow Leopard.

Update 2009-08-29: We finally have more reliable confirmation that 32bit Macs will be able to run Java 6 on Snow Leopard. This is a big deal and I don’t understand why Apple hasn’t made this more public.

Update 2009-09-02: More information on this topic, including how-tos for getting Eclipse running with Java 6.

Update 2010-12-05: Java on Mac OS X Lion: the redux. News on what will happen to Java on Mac OS 10.7.

الجمعة، 17 يوليو 2009

Eclipse E4 is going even further in the web direction

The latest version of E4 contains “web components”. It warms my heart that they are using Dojo (=true client-side technology) for some of their experiments. JavaScript OSGi modules also look cool (don’t get too excited, though: they are for server-side JavaScript).
Update 2009-08-04: Check out SWT Browser edition. Its goal is to enable cross-compilation of SWT applications to something that runs in the browser. Flex cross-compilation is working, other approaches are under investigation.

الأحد، 21 يونيو 2009

I think I figured out Apple's Java 6 strategy

Apple has been really negligent with Java: First there wasn't a Java 6 for ages, then it only ran on 64 bit machines. And while all current Macs are 64bit, this excludes a lot of Intel Macs. Thus, targetting Java 6 on the Mac was not practical. Fortunately, one of the WWDC 2009 sessions was “Java 6 on Snow Leopard”:
As Snow Leopard moves to Java 6, learn modern techniques for the best possible Mac experience while maintaining cross-platform compatibility using the latest version of Java. Find out how Mac OS X continues to build on its strong Java support with new UI enhancements, new APIs, and a next-generation Java Applet browser plug-in.
Now I think I understand Apple's Java 6 strategy:
  • Don't support PowerPC, ever.
  • Initially support Java 6 as quickly as possible on currently sold Macs (with the limited resources Apple has allocated to Java). This meant support for 64bit Intel only.
  • Eventually support all Intel Macs. Well, at least I don't see any other way of interpreting the WWDC session (if Java 6 is standard on Snow Leopard and Snow Leopard runs on all Intel Macs...).
And while I'm still underwhelmed, this is acceptable. What is not acceptable is not having communicated this strategy for years.

الاثنين، 8 يونيو 2009

JavaFX authoring tool

The blog post “JavaFX Authoring tool demo at JavaOne 2009 (with video)” shows two videos of a prototype of the JavaFX authoring tool in action. Very nice, the binding stuff reminds me a bit of the Mac OS X interface builder. I still wonder though, how useful binding is in multi-threaded settings.

الجمعة، 1 مايو 2009

Multiple dispatch: a fix for some problems of single dispatch (Java etc.)

Almost all well-known object oriented languages (Java, C#, JavaScript, Python, Ruby, ...) have single dispatch: Methods are chosen depending on the (single) receiver of a message. On the other hand, there is multiple dispatch which is an interesting mix of functional method selection with mutable state. It is used in less-known object-oriented languages such as Common Lisp.



In this article, we'll first look at Java's single dispatch and Java's overloading and then use what we have learned to understand multiple dispatch and how it solves some design dilemmas that can't be solved with single dispatch.



Let's start with dynamic dispatch:

    public class Empty extends Object {

@Override
public String toString() {
return "Empty";
}

public static void main(String[] args) {
Object empty = new Empty();
System.out.println(empty.toString());
}
}



What is the output of this program? It is “Empty”. If this seems obvious, it is because you are already very familiar with dynamic dispatch: Java determines at runtime what class an instance belongs to and chooses the appropriate, possibly overridden, method. For the example above, this means that we don't use the toString() method from class Object, but the toString() method from class Empty. In some languages, such as C++, you have to explicitly state that you want dynamic dispatch.



Now on to overloading, another way of picking a method implementation.

    public class Printer {
public void print(String str) {
System.out.println("String: "+str);
}
public void print(Object obj) {
System.out.println("Object: "+obj);
}
public static void main(String[] args) {
Object obj = "abc";
new Printer().print(obj);
}
}

Here the output is “Object: abc”. The method implementation is chosen statically, at compile time: Internally, the compiler uses the static types of the method arguments to disambiguate the method names. This time, the result is unexpected, even really good Java programmers that I've asked get it wrong. Due to dynamic dispatch feeling so natural for the receiver of a message (=“this”), we expect it to work the same for the arguments. There is a kind of asymmetry between the receiver and the arguments of a method and that asymmetry is reflected in the invocation syntax, too.



With multiple dispatch, methods become top-level constructs. This is similar to implementing a single dispatch method “foo” with two arguments as a static method:

    public static void foo(this, arg1, arg2) {
if (this instanceof A) {
...
} else if (this instanceof B) {
...
} ...
}

The message receiver “this” becomes just another argument and all variations of the method are united in a single place (having this kind of view on a method helps with understanding implementations that use polymorphism, but I digress). Instead of the myObj.foo(x,y) you now invoke foo as foo(myObj,x,y). This is still single dispatch. Multiple dispatch nests instance-of checks for arg1 and arg2 inside the checks for “this”. Only after checking the types of all arguments do we decide which variation of the method to use. Common Lisp calls foo a generic function and the code snippets inside it methods.



Note that the if statements were for illustration only, languages with multiple dispatch have efficient algorithms for performing the checks and selecting a method.



What advantages does this have?



A generic function can “belong” to several classes. This helps whenever method arguments are not true parameters (data), but rather collaborators (that offer services) for an algorithm. For example, if you have a method Database.export(Filesystem,UserFeedback), this method might contain as many Database invocations as Filesystem invocations. The special case of binary operators as methods exhibits the same difficulty: Should the operator “String + Integer” be considered part of class Integer or part of class String? It is for a reason that UML has special diagrams for collaborations and that these diagrams cross-cut classes.



One more example of collaborating objects is the visitor pattern: It is a clumsy simulation of multiple dispatch with single dispatch. What you have at its core is the object for the algorithm collaborating with the object for the data. With multiple dispatch, things are much simpler, there is less code to write and the data objects do not have to be prepared for visitors. Interestingly, even the explicit object for the algorithm disappears, because the generic function replaces it.



Another area where the asymmetry of single dispatch shows is with the null value. For example, "abc".equals(null) is OK while null.equals("abc") causes an exception (and is not even directly syntactically correct). If you introduce null checks as selection criterion for methods, then handling null values is simple with multiple dispatch.



Extending a class is trivial with multiple dispatch, just create a new generic function that accepts instances of that class as its argument. With Java, people often overlook external static methods that actually extend a given class, because they don't know where to look. For example, if you don't know Java well, you might be puzzled as to why List has no sort() method. If you do, you know that the class Collections has a static method sort(List) that you have to use. In languages with multiple dispatch, one already assumes that in general, a generic function is relevant for several classes. The development tools help one with finding all functions that apply to a given class, making sure that code is re-used instead of re-invented.



Having code tightly integrated with the data is less desirable in settings where you serialize objects. With generic functions, code and data are separate and it is easier to use the same data structures on the server and the client. The server can host a lot of code that generates or modifies data. The client only has to display the data and lets the server handle the more complicated stuff. This is a frequent scenario when doing client-server communication with the Google Web Toolkit. As Java does not have generic functions, the server-only functionality has to be moved to external static helper methods. Consequently, things are even less encapsulated, slightly messy and one loses polymorphism.



Predicate dispatch



A generalization of multiple dispatch is predicate dispatch. With multiple dispatch, the methods of a function are selected based on the types of the arguments. With predicate dispatch, more complex conditions can be specified. This simplifies changing the behavior of an instance depending on its state and obviates the need for the strategy pattern. For example: Let's assume that an instance of class Bar has to behave differently if an error flag is set to true. The relevant generic functions will contain one method that is invoked if the flag is true and another one if the flag is false. Attached to the first method is an explicit selection condition such as myBar.error. The second method has a condition such as !myBar.error. These selection conditions are additional ways of classifying instances. One could say that myBar changes its class depending on the value of its field error.



Conclusion



We have seen that multiple dispatch can do several things that single dispatch can't. But I think that both are complementary. Message passing is a nice and clean metaphor for method invocation that works well with distributed computing. It views objects as components that provide services. On the other hand, objects-as-data result in phenomena (binary operators etc.) that are best implemented with multiple dispatch.


Further reading



The basics in depth




Advanced topics




Languages close to Java with multiple dispatch


السبت، 28 مارس 2009

Unit testing with Eclipse and converting a Map to String

When testing with JUnit, one often has to compare the expected result of a computation with the actual result. A convenient way of doing this is to turn the actual result into a string and then compare two strings. On one hand, the convenience is because converting the actual result to string is often simpler than constructing an object for the expected result (the final decision between these two options depends on which one of the two has applications beyond unit testing). On the other hand, Eclipse helps with string comparisons in two ways:
  • Preference “Java → Editor → Typing → Escape text when pasting into a string literal”: Allows one to quickly turn blocks of text into Java string literals for the expected result.
  • Built-in diff for assertEquals(): If assertEquals() fails for two strings, Eclipse shows a nice diff of the results. This makes it easy to figure out what went wrong.
Obviously, the output has to be deterministic which is a problem for, say, HashMaps. With this motivation in mind, now a question: What is the quickest way of turning a Map into a string where the keys are sorted?
    public static <K extends Comparable<? super K>, V> String toStringSorted(
Map<K, V> map) {
return new TreeMap<K, V>(map).toString();
}
Select the text between the braces to make it visible.

الأحد، 1 فبراير 2009

What's new in client-side Java?

Client-side Java's evolutionary leap” gives a great overview of interesting things that happened for client-side Java in 2008. Recommended additional reading:

الاثنين، 14 أبريل 2008

Online Eclipse E4? Lack of imagination! [Update]

Related posts: "Improving code browsing in Eclipse", "Eclipse 4 wishes: simplification first, then innovation".



In this post, I'll take a look at where desktop and web applications are heading. Eclipse E4 could be a major player, but its vision is too limited. First, I'll summarize the current state of application affairs.



Recent developments in web applications:

  • Offline modes and databases (Google Gears).

  • Run them as separate applications via Mozilla Prism.

  • Write them like a desktop GUI application, be it via Dojo or via GWT.

  • Have bidirectional communications with a server (Comet).

  • The server is getting leaner, becomes mostly a service provider, while the clients do much more work.

GUI applications

  • receive updates via the internet.

  • provide help texts in HTML.

This makes it seem inevitable that both kinds of applications will meet in the middle. So what will this middle ground look like?

  • Ubiquity: Applications are available anywhere (where you have online access) and there is no installation necessary. Update are completely unobtrusive.

  • Synchronization: A corollary to ubiquity, you want your data to be ubiquitous, too; not just your application. Applications will synchronize with a server, in a fashion that mimics distributed version control systems.

  • Integration: Applications are first-class citizens in a desktop environment.

  • Mash-ups: You build mash-ups by orchestrating web services and exchanging user interface components.

  • Stability: Applications run safely separately and don't affect some kind of browser, be it by slowing it down or by crashing it.

  • Rich content: appears everywhere, it includes images, sound and movies.

What I would love to see is more thinking about how we can move desktop applications closer to this middle ground. For example: Why is Java web start so close to the above outlined ideal and yet not nearly used as much as Ajax applications? How can we make desktop applications simpler to maintain? How can we build synchronization into every application? How can desktop applications do mash-up-style data and GUI integration?



In my opinion, tools like GWT get it right, while the Eclipse E4, at least from what I've read about it so far, does not. The former is an excellent intermediate solution that will be easy to evolve into what is to come. The latter feels more like a frantic push to be web-enabled, somehow. RAP, which has been quoted as an E4 inspiration, is a bit like an anti-GWT and relies a lot on the server to keep state. Pursuing this path gives you the worst of both worlds: You have sluggish web applications and do not evolve the state of desktop applications, either.



Any comments? Am I right in bashing E4's web ideas or did I just misunderstand?



Disclosure: This post has been partially triggered by "Who Needs an Online IDE?".



Update: The newest generation of applets can be dragged to the desktop to become a Java web start application. This is really cool: You can quickly test-drive an application as an applet, but also turn it into a proper application for long-term use.

الاثنين، 17 مارس 2008

Improving code browsing in Eclipse [Update]

Related posts: "Online Eclipse E4? Lack of imagination!", "Eclipse 4 wishes: simplification first, then innovation".

Again, I want to prevent ideas of mine from getting lost, so I'm publishing my comments to an Eclipse bug report as a blog entry.

Faceted browsing for Java code

I'd love to have a universal code browsing solution that uses "facets" (tags with values). An example of well-done facet navigation is iTunes where you have facets for songs such as composer and title. If you look closely, there is quite a bit of information attached to a method that could be considered tags/facets: Visibility, static vs. non-static, annotations etc. JavaDoc's @category just adds one more dimension here. With a facet browser, one could formulate queries such as the following in a very natural way: "Give me all public methods with annotation @Remote that belong to category 'persistence'". This browser should optionally access all methods (of all classes) in order to serve as a universal query mechanism.

Improving the outline: nested methods, method groups

We have written a research prototype that improves just the outline view in two ways:
  • Nested methods: If a method n is private and only used by a method m, then file n under m in the hierarchy (thus, n is not visible at the top level, any more). The reasoning here is: "extract method" is a great refactoring for cleaning up code, but it unnecessarily clutters the top level of the code outline.
  • Method groups (this can be replaced by @category!): If a sequence of methods is preceded by a commentary //--------- foo then these methods will be filed under a node "foo" in the hierarchy (= one additional level of nesting)
For method groups, one can also view categories as tags and, instead of introducing another level of nesting, list the categories as toggle-able buttons that filter the outline:

+-----------------------+
| o | x | @ | # | * | + | <-- icons
+-----------------------+
| (read) (write) (sort) | <-- buttons
| (init) |
| |
| - prepareForSorting() | <-- outline tree
| - writeContents() |
| ... |
+-----------------------+

Thus: Selecting a button filters the outline, unselecting it undoes the filtering. Another possibility is to have filter buttons for "private", "public", "static" etc, too.

This might also be complementary to the nesting approach.

Update: At EclipseCon 2008, there is now talk about "E4", the next generation of Eclipse. There is a lot of talk about expanding the platform (ReSTful web services etc.). Voices to simplify are there, as well; let's hope that they will not be ignored: