Category Archives: Desktop Java

Dependency Injection in both Ruby and Java

Dependency Injection: Vitally Important or Totally Irrelevant? by Jim Weirich at OSCON 2005.

This is a great presentation about Dependency of Inversion (and why you might not need it). It nicely compares and contrasts Java and Ruby. It underscores why I really enjoy programming in Ruby: it is very fluid. For example, classes are objects and can change at runtime.

It also answers the question: Do you need something like Spring or HiveMind in Ruby?

Quick tip: How to call parent outer class methods from an inner class

A friend of mine asked me about this and googled: “java inner class parent methods”. Hopefully this will help other Java programmers who run into this same problem.

[By the way, I neither condone nor promote these naming conventions. :) ]

Say you have an interface Foo, with a method bar().

Also say that you have a FooImpl class that implements Foo with a method bar(), and inside of it you have a NodeImpl inner class that also implements Foo, which means that it too has a method bar(). Say that NodeImpl also has another method doSomething(), which needs to call bar(), but specifically the bar() of the parent, FooImpl.

Problem: If you just call bar() from inside the inner class NodeImpl, you will get the inner class’s bar(). This is because of scoping. So how do you solve this?

Answer: Call FooImpl.this.bar() or in general, call ParentClass.this.method() from your inner class.

Iterating over OrderedCollections

One of the things you want to do after having an OrderedCollection (aka List or Array) is to iterate over the elements. I’ll look at the languages I’m interested in: Smalltalk, Java, Objective-C, Ruby, Python, and C#.

First off, Smalltalk. I think they got it right, by having blocks / closures as being first-class elements of the language. You can re-use blocks and each block has its own scope. Here’s how to iterate in Smalltalk:

list do: [ |item| item doSomething]

Next up, Ruby. Ruby’s next because it comes closest to Smalltalk. It too has blocks. Here’s how to iterate in Ruby:

list.each { |item| item.doSomething }

Since we just did Ruby, let’s see how Python iterates:

for item in list:
  item.doSomething()

And why not… C# iteration:

foreach (ItemClass item in list) {
  item.DoSomething();
}

I’ve saved Java and Objective-C for the last because they are a bit more complicated than the rest, at least historically.

Java, pre-Java 1.5 / 5, many programmers used typed arrays and then used a for loop to iterate:

ItemClass[] list = new ItemClass[size];
// fill in the list
for (i = 0; i 
You could have also used either an Enumerator (if using the legacy Vector) or Iterator/ListIterator if using List. Java 1.5 gives you a much cleaner way to iterate:
for (ItemClass item : list) {
  item.doSomething();
}

Finally, Objective-C has something called NSEnumerator. Apple advises programmers to iterate this way:

NSEnumerator *enumerator = [list objectEnumerator];
id item;
while (item = [enumerator nextObject]) {
    [item doSomething];
}

But many of us aren't quite happy with this way of doing things. There's no type information, since id is any object. Making a method call, assigning to an object reference, and testing a boolean all in the while test is too much in one place. Jonathan 'Wolf' Rentzsch has a great page that dissects this and he offers a nice macro that boils down to:

nsenumerate(list, ItemClass, item) {
  [item doSomething];
}

I think that while this is much better, it just doesn't seem like it is in the right order. I modified Wolf's macro a bit and renamed it to "foreach":

foreach( ItemClass, item, list )  {
  [item doSomething];
}

Note that for these macros to work, you need to set the Project Setting "C Language Dialect" to either "C99" or "GNU99".

All of these seem to be good at limiting scope and lifetime of the item variables. There are two styles in use: the block iterator and the "enhanced for" iterator. I prefer the block iterator, but it doesn't seem to be available for most languages. The "enhanced for" is the next best and with the slight modification to Wolf's nsenumerate macro, they all look very similar.

Comparison of OrderedCollections in Smalltalk, Java, Objective-C, Ruby, Python, and C#

In my last post, I compared the collections classes at a high level. Now I’m diving into the one that is most often used, the OrderedCollection.

What’s an OrderedCollection? It is the collection class in Smalltalk that supports ordering. Seems straightforward, but why use the Smalltalk name for it? Why not the more popular List or Array? Because Smalltalk and its collection classes have been around for much longer (over 25 years) than the other languages I’m comparing. All the other languages actually derive in some fashion from Smalltalk.

I haven’t done that much Python and C#, but I figured I should check them out while I am at it. For the others, I have done quite a bit and I wanted to take a step back and look at how each compares.

Here’s a table that compares the API for each language:
(Note that I’ll use “list” since it is shorter than “OrderedCollection” so it can fit nicely in this table.)

Smalltalk Java Objective-C Ruby Python C#
OrderedCollection List – ArrayList NSArray / NSMutableArray Array List IList – List
list := OrderedCollection new List<Type> list = new ArrayList<Type>() NSMutableArray *list = [NSMutableArray array]; list = Array.new or list = [] list = [] IList list = new List();
list size list.size(); [list count]; list.length len(list) list.Count()
list isEmpty list.isEmpty(); not included list.empty? ? ?
list add: item list.append(item); [list addObject: item]; list.push(item) list.append(item) list.Add(item);
list addAll: anotherList list.addAll(anotherList); [list addObjectsFromArray: anotherList]; list = list + another_list list.extend(anotherList) list.AddRange(anotherList);
list remove: item list.remove(item); [list removeObject: item]; list.delete(item) list.remove(item) list.Remove(item);
list indexOf: item list.indexOf(item); [list indexOfObject: item]; list.index?(item) list.index(item) list.IndexOf(item);
list includes: item list.contains(item); [list containsObject: item]; list.include?(item) item in list list.Contains(item);
list at: index list.get(index); [list objectAtIndex: index]; list.at(index) or list[index] list[index] list[index];

Now I’m going to argue against using Array as a name, because people tend to confuse it with C-style arrays. Most of these languages can interface with C (usually to optimize certain sections of code or to interoperate with legacy libraries) and so it is nice to not have two concepts referred to via the same name. So ideally I’d like to see Ruby change Array to List and Obj-C/Cocoa use NSList and NSMutableList. I doubt I will make this happen, however. :)

Next, more heresy: Java and C# have backwards syntax for constructors. Why don’t they just make it like every other method call and have a “new” method at the class level like every other language? (Not sure if Python’s List is actually a class.) Hmm… maybe someone can contribute this for Java 6?

Nobody seems to agree on a method name for size, count, or length. Note that Python doesn’t seem to have a method for this, rather a len() function. Also Python doesn’t have an includes: method, but an “in” language operator.

Java seems to mirror Smalltalk nicely, with a few wording changes and a C++-like syntax. I included the type-safe Java 5 syntax for the Java constructor to show how it makes life a bit safer with compile-time type safety, but also clutters the code a bit to accommodate the type. Note that this clutter is saved later when you get rid of casts.

Objective-C also mirrors Smalltalk, but seems to add “Object” everywhere, making them verbose. I wouldn’t mind if this got replaced by a more bare protocol later on.

Actually, Obj-C has a language feature called “categories”, which lets you extend an existing class without creating a subclass. So does Ruby and possibly Python. Java does not let you do this. Not sure of C#. I think I will try and see if creating and using a new Obj-C category and Ruby mix-in that lets me use the Smalltalk-canonical method names will be easier, since I will only have to remember one set of method names.

Note also that Objective-C has to wrap method calls in square brackets.

Also Objective-C (actually Cocoa’s Foundation Kit) has both an immutable and a mutable version. The immutable version gives you thread-safety and is faster. I addressed this in the earlier post about collections. Note that Java’s ArrayList is not thread-safe by default.

Ruby has an interesting convention of using ? at the end of its method names instead of using “is” and camel-casing. Note that camel-casing is discouraged in Ruby. Instead, the preferred Ruby convention is a_long_method_name instead of aLongMethodName. It also seems to be derived from Python as well as Smalltalk, but is more object-oriented. While it has the [] operator like Python, it uses methods instead of len() and the keyword in.

C# looks just like Java. Note that C# 2.0 has Generics support, like Java 5. The only thing that is odd is that it uses a different casing model, with the first letter of the method name uppercased.

Next: iterating over OrderedCollections.

Comparison of Collections in Smalltalk, Java, Objective-C, Ruby, Python, and C#

Why look at collection classes? Well, after reading a bit about the language syntax and writing “Hello World”, I think the next thing you should learn about a language/framework is its Collections classes. Its one of the things that makes programming in a higher than C level language more powerful. Its also one of the most basic. You’ll find that the other parts of your chosen framework whether it is Cocoa, Eclipse, Rails, or whatever, uses these collection classes heavily.

Also, I’ve been writing code in these different languages, so I’m using this to help me get straight what the APIs are like for each collection class. Hopefully this will help you out if you’re transitioning from one language to another.

Let’s see what each language has to offer in terms of the 3 basics: OrderedCollection, Dictionary, and Set. Dictionary holds key/value pairs and Set holds unordered, unindexed, unique objects. I’m using the Smalltalk class names as the canonical names, since it is the GrandDaddy of all object-oriented languages.

Smalltalk Java Objective-C Ruby Python C#
OrderedCollection List – ArrayList NSArray / NSMutableArray Array List IList – List
Dictionary Map – HashMap NSDictionary / NSMutableDictionary Hash Dictionary IDictionary – Dictionary
Set Set – HashSet NSSet / NSMutableSet Set [1] ? ?

Some brief thoughts on the language differences:

Objective-C / Cocoa, though more specifically the Foundation Kit, which is the non-UI related frameworks, offers immutable and mutable versions of each collection. This is unique and seems like a premature optimization at first. However, if you’ve ever read Josh Bloch’s Effective Java, you’ll realize that he recommends using immutable objects whenever possible, to reduce errors and ensure type-safety.

Also, all the Foundation Kit classes start with “NS”, which stands for NeXTStep. This is a workaround for not having namespaces as part of the language.

Java has a strict separation of interface and implementation. This is nice in one sense, but cumbersome in another. Its too bad you can’t just say new List() and have a factory that you configure in your application that tells you when to instantiate which implementation.

Also, Java has the largest and thus hardest to memorize collections API. There are multiple implementations of each interface. I included the ones that should be used by default for most cases. There are old versions of APIs (Vector and Hashtable) which tend to confuse veterans who used to use them and beginners alike. There are typesafe (Java 5/1.5 only) and non-typesafe versions (which involve casting.) Before Java 1.5, many programmers would just use typed arrays to get type safety. There’s also immutable versions of collections, but these are not protected via API, instead they throw UnsupportedOperationExceptions at run-time.

Java and C# have type-safe at compile-time collections. This is both good and bad, but in my opinion, it is rarely a problem in practice with the dynamically-typed languages. In general, C# seems to behave similarly to Java.

[1] UPDATE: Set available for Ruby as part of the Standard Library. Thanks to John Labovitz for pointing this out.

Java 5 for OS X 10.4 Tiger is here

Apple released Java 5 for OS X today. (Also known confusingly as both “Java 2 SE 5.0 Release 1″ by Apple and as Java 1.5 to Java developers who are used to the 1.x versioning scheme.) It only runs on OS X 10.4 Tiger, so that’s a good enough reason by itself for Java developers on Mac to get Tiger. Of course, there’s tons of other reasons like Spotlight, Automator, Dashboard, etc.

Eclipse runs fine on it, with the exception of starting it from Spotlight. But just start it from Finder, command line, or the Dock and you’ll be fine.

Thanks to Marcello for pointing this out on the Eclipse-Mac group

Gauging market demand for different IDEs via SimplyHired.com

I was perusing the popular delicious links and found a new job site: SimplyHired, which bills itself as “building the largest job database on the planet.” Its pretty fast and lets you do searches without any commitment.

So, I searched for the different Java IDEs to see what came up. Here’s the results, ranked by most job matches to the least:
Continue reading

64 bit JVM, here we come

I’m planning my WWDC trip and I noticed that the preliminary schedules are up now. BTW, if you’re planning to go, I’d book soon, since the early registration is ending soon.

One of the sessions caught my eye: “64-bit Java Virtual Machine Exposed“.

With the new 64-bit Java Virtual Machine you can now access a larger Java heap from your high-performance Java server application. 64-bit Java enables Java heaps much larger than the current 2Gb limit. We will focus on the changes required to use 64-bit Java and the implications associated with it.

Ah yes… this is why I need to buy a G5 with 8GB of RAM. I wonder if Eclipse will be supported on this configuration. I know that Eclipse already supports Linux/GTK on 64-bit AMD64.

Also scheduled at the same time (5:00-6:30 on Friday) is “The Next Phase of Eclipse’s Development“.

Eclipse has quickly become one of the most widely used cross-platform Java development environments. In this hands-on session, we’ll show you how to get started on your next Java project, get over the initial hurdles, and become comfortable with Eclipse. Learn from other experienced developers who are using Eclipse to build Java applications today.

I’d like to go to this session too, not so much to learn about Eclipse. I’m still processing stuff from EclipseCon. But I’d like to get developers excited about using Eclipse on OS X and let them know that there is a community around that combination. It’s too bad these two are at the same time. Moving one of them to the 2:00-3:30 time slot would be good us developers who are doing Eclipse on OS X and also wanting to take advantage of the 64-bit JVM.

The state of Java on Mac OS X

James Duncan Davidson wrote about the state of Java on Mac OS X and I saw a comment that was dead-on:

I agree Apple is focused more on server-side Java on the Mac, but keep in mind that there is at least one really important Java desktop app that server-side developers care about: Eclipse. If Eclipse doesn’t run well on the Mac, all of those server-side Java developers go elsewhere…
-Andrew Shebanow

I don’t know if all those server-side Java developers actually would switch back to Linux or a Windows machine, but I think the point is that Eclipse needs to run well on Mac, period. BTW, there is an Eclipse on Mac users group.

Later, James added:

Important tasks like building GUI applications. There are a few decent Java based GUI apps out there. However, I find it telling that the best GUI applications out there written in Java are IDEs in which to develop Java code. I’ve seen a handful more, usually at the pace of one a year, that work well and provide a great user experience. But in general, the evidence says that Java, or at least Swing, isn’t the greatest language or library for building GUI applications with. SWT may be, but that still remains to be seen.

I’ll add some more observations:

1. Eclipse RCP Apps (which are built with SWT) will probably change things. On OS X, they are built on the Carbon framework currently and they look and feel native. More importantly, RCP makes building a full featured app easier. With Swing, you have had to build an app framework yourself. That is not a trivial task. I know since I have played a part in building and maintaining one.

That’s one of the reasons why the IDEs are the main Java apps right now, since they have enough people to build these application frameworks with enough left over to build the actual Java tooling bits. Fortunately for the rest of us, the Eclipse team is now sharing that wealth with us to build desktop apps (they call them rich clients).

2. Enterprise desktop apps that need to run multi-platform (Windows, Linux, OS X, etc) are usually written in Java. However, you don’t see many of these apps because they’re not marketed towards consumers.

3. Apple does have good support for Java, they had a strong presence at EclipseCon, and they are currently looking for an engineer (who knows SWT among other things) to improve the Java support even further.

I think Apple will probably continue to ensure a good Java experience on OS X, but continue to expose the OS X specific APIs mostly just to Cocoa and Carbon. That is ok, since they are (mostly) targeting different markets: Java / RCP -> Enterprise Cross-Platform Desktop and Objective-C / Cocoa -> Consumer OS X Desktop.

Proposal to reduce repetition with Swing and SWT listeners

DRY – Don’t Repeat Yourself

We know that this is good, since it reduces code maintenance, so why do we persist with writing listeners like this: (Note that this is example is written with SWT; Swing looks almost the same.)

        final Button button = new Button(shell, SWT.NONE);
        button.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                text.setText("Hello World");
            }
        });

If you’ve got lots of these lying around, well first off, you should try using an application framework like the Eclipse Rich Client Platform or the Spring Rich Client Project. But if you don’t (and even if you do, you still need to deal with wiring interface elements together), then you can make a code template in your IDE to generate this idiom. However, you’re stuck with maintaining all this code, plus the code is not as clear as it could be.

What if instead, your code looked like this?

        final MyButton button = new MyButton(shell, SWT.NONE);
        button.onPress( text, "setText", new Object[] { "Hello World" } );

Unfortunately, because Java places a higher value on security of its classes than expressiveness, you cannot add methods to an existing class (which you can do in some other languages). Also, you cannot subclass SWT widgets. So, instead, we use a utility class, which is slightly less readable.

        final Button button = new Button(shell, SWT.NONE);
        ButtonUtils.onPress( button, text, "setText", new Object[] { "Hello World" } );

This is better, since it takes what used to take 5 lines of code to express and put it into 1. It also focuses on what should happen when the button is pressed, instead of that being dominated by the supporting code.

Swing introduced something similar back in Java 1.4 called EventHandler. This generates a dynamic event listener. For example:

        JButton button = new JButton( "Hello World" );
        button.addActionListener( (ActionListener) EventHandler.create(
                                                        ActionListener.class, textField, "setText", "source.text" );

Note that this has the disadvantage of having to grab parameters to pass to the target object from the ActionEvent object. That’s why I stuffed “Hello World” as the text of the JButton for this simple example.

Here is the main piece for ButtonUtils. The code for findMethod is relatively simple, but I can post it if people want it.

    /**
     * Registers an object that has a method named methodName,
     * which is called when the button is pressed.
     * 
     * @param button
     * @param instance
     * @param methodName
     * @param parameters
     */
    public static void onPress( Button button, final Object instance,
                                                    String methodName, final Object[] parameters ) {
        final Method method = findMethod( instance, methodName, parameters );
       
        button.addSelectionListener(new SelectionAdapter() {
            public void widgetSelected(SelectionEvent e) {
                try {
                    method.invoke( instance, parameters );
                } catch (IllegalArgumentException exception) {
                    exception.printStackTrace();
                } catch (IllegalAccessException exception) {
                    exception.printStackTrace();
                } catch (InvocationTargetException exception) {
                    exception.printStackTrace();
                }
            }
        });
    }

So what do people think about this? Does anyone use something like this in their code? The advantages are: 1. DRY, 2. less code overall, 3. somewhat clearer (could be clearer with Java language changes). Disadvantages: 1. reflection isn’t refactored easily, 2. reflective code doesn’t take advantage of static type checking at compile time, 3. potential for reflection exceptions.