MattHicks.com

Programming on the Edge

Java Delegates in xjava

Published by Matt Hicks under , , , , , , on Tuesday, July 07, 2009
I posted over a year ago about Delegates in Java, and since I kicked off an exploration of the functionality I'm providing in my xjava framework with my previous post I thought I would continue with my newest iteration of the Delegates concept as utilized in xjava.

Until you use a language like Scala or Flex that has full delegate support, you can't really appreciate what it is you're missing. As Java programmers we take it for granted that if we need to do some "work" we usually have to create a Runnable implementation that implements the run() method to do the work we need to do:

Runnable r = new Runnable() {
public void run() {
... do work ...
}
};
passWorkOff(r);

However, in other languages that support Delegates you can pass methods/functions as parameters to methods/functions to simplify this process greatly. Consider the alternative:

public void someMethod() {
passWorkOff(this.doWork);
}

public void doWork() {
... do work ...
}

This minimizes the amount of custom/anonymous classes you must create in order to pass a unit of work off.

Unfortunately in Java this functionality is not (yet) supported. Many people have created work-arounds, generally with Java Reflection, but none can support the elegance of the native delegate support other languages have.

I may be known for my rants, but I won't leave you hanging here with a negative thought of Java, I love the language too much to do that. Besides, I have a framework to promote, so lets get to it. :)

In xjava there is a simple interface Delegate:

public interface Delegate {
public Object invoke(Object ... args) throws Exception;
}

The invoke method takes a varargs of Objects and returns an Object. It's pretty straight and simple, but the out-working of the implementations are what add significant power to this concept.

There are several different implementations, but by far the most used and most powerful is MethodDelegate. In our above example of using delegates in other languages to pass a function, this imlementation fulfills that role with the following call:

MethodDelegate delegate = new MethodDelegate(this, "doWork");
passWorkOff(delegate);

This presumes that the passWorkOff method takes a Delegate as a parameter. Like I said, this isn't as good as native support, but it's pretty simple and although you lose the ability to have compile-time checking that you're referencing a valid method, it will throw an exception at runtime if the method referenced is unable to be found.

MethodDelegate has some extremely powerful features that have been added to make it even more powerful though. One such feature is the ability to mix and match when arguments are applied to the method being invoked. Say you have the following method you want to invoke:

public void doSomething(String name, String address) {
....
}

Now, at creation time of the Delegate you know what "name" is, but in the place you wish to use the delegate you only know the address. See the following:

public void someMethod() {
Delegate d = MethodDelegate.createWithArgs(this, "createEntry", "John Doh");
processAddress(d);
}

public void processAddress(Delegate d) {
String address = "123 Nowhere Rd.";
d.invoke(address);
}

public void createEntry(String name, String address) {
...
}

Notice that at creation time of the Delegate "John Doh" is passed in. This is assigned in the Delegate instance as the first argument to the MethodDelegate. Now, when d.invoke is called in processAddress rather than requiring both name and address just address is necessary to be passed since name has already been assigned.

This makes it incredibly easy to put parameters into the method when you're ready to do so rather than applying everything in one place.

Delegates in xjava also make it easy to abstract away from the underlying way data is being retrieved or being assigned. For example, in the above processAddress method, it simply takes a Delegate and invokes it passing the address to it. If you decided later that you would rather assign this to a field of an object rather than calling a method you would simply replace someMethod with this:

public void someMethod() {
Delegate d = FieldDelegate.get(person, "address");
processAddress(d);
}

This presumes the "person" reference is an object with a String "address" field represented within it. The FieldDelegate doubles for getter and setter since passing a value will apply it to the field and invoking without any arguments will get the value from it.

There are also implementations for CallableDelegate and RunnableDelegate that are self-explanatory.

As seen by the interface for Delegate it is extremely easy to create your own implementations of Delegate for whatever scenario you may want to support and abstract away the details of where and what you are actually accessing and though this isn't as elegant as it could be if Java supported delegates natively, it still provides a very decent mechanism for abstracting and simplifying the process of passable work.

See the xjava project for more information:
http://xjava.googlecode.com

Feel free to look at the source code directly:
http://xjava.googlecode.com/svn/trunk/src/org/xjava/delegates/

The Death of Beans

Published by Matt Hicks under , , , , , , on Wednesday, July 01, 2009
My previous post was more of a rant about the frustrations of Java Beans:

Have Beans been holding us back?

I stated at the end of my post/rant that my next post would be about what I suggest as the viable successor to Java Beans. To that end, I begin my discussion about properties.

Though I would like to claim the idea of properties as all my own invention, I cannot and the concept was even new to me when I first read about them here:

https://bean-properties.dev.java.net/tutorial.html

This is not really a new concept, but rather an attempt in Java to solve the problem other languages like C# and ActionScript solve with encapsulated properties that allow you to make calls like:

object.name = "Something";

Though this would appear to a Java developer as a public field being set to a value, in these languages there is a feature to provide special functions/methods for "set" and "get" of the private field and simplifies getter/setter functionality while maintaining a clean and consistent coding experience.

Unfortunately there is no such functionality built into Java and if you want to provide anything beyond assignment of fields to values you must use methods to accomplish this.

With Java 1.5 comes generics which really for the first time make properties practical without a lot of extending of classes. So take a simple example:

public class MyTest {
private String name;

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

Now, this is what it might look like using Properties:

public class MyTest {
public final Property<String> name = new Property<String>(null);
}

Properties have set(T t) and T get() methods that replace getters and setters, so a call to change the value would look like:

myTest.name.set("Testing");

Compared to:

myTest.setName("Testing");

They are about the same amount of actual code. What's great here though is that your Property object could contain much more additional functionality that you otherwise would have to inject yourself. For example if Property had the ability to addPropertyChangeListeners:

myTest.addPropertyChangeListener(myChangeListener);
myTest.name.set("Testing"); // Will now invoke myChangeListener when called

Further, you could have something like NotNullableProperty that extends Property and throws a NullPointerException if you try to call set with a null value:

public class MyTest {
public final NotNullableProperty<String> name = new NotNullableProperty<String>("");
}

Now a call to:

myTest.name.set(null);

Will throw a NPE and thus remove the need for you to ever have to check if "name" is null. This hopefully gives a slight grasp of the benefits this begins to provide.

Now, I mentioned above the article that really got me thinking this direction, but ultimately decided to write my own Property implementation because of some of the limitations and performance problems I saw with that implementation. Further, I had a lot of additional features I wanted to provide myself...and am often accused of wanting to write everything myself anyway. :)

This post isn't meant to push people to use a specific Property API but just to consider the methodology change even if they decide to write their own. After all, it only takes a few lines of code to create the base for your own Property class:

public class Property<T> {
private T t;

public T get() {
return t;
}

public void set(T t) {
this.t = t;
}
}

From there you can add any desired functionality: property bindings, value validation, property change listeners, observer/observable functionality, null checks, etc.

Though I don't want to push anyone to necessarily use a specific API, I will give reference to my own Property API for anyone interested in using it as it provides a great deal of functionality and I'm heavily using it in nearly all new programming projects these days and it supports filtering, change notification, property delegates, binding, read-only, adjusters, and much more. It is part of my xjava project:

http://xjava.googlecode.com

To see the source code for my Property API in SVN:
http://xjava.googlecode.com/svn/trunk/src/org/xjava/bean/properties/