Archive for the 'java' Category

Javascript will be the Next Big Language

Wednesday, April 23rd, 2008

I’m on JavaScript kick lately. Or rather, I have been rediscovering it ever since I read the series of Steve Yegge’s blog posts on JS and Rhino and his predictions for the next big language. I really think he is right - JS will be the next big thing that will trump Ruby from it’s pedestal or at least become its viable competitor as the next big dynamic scripting behemoth. Why? I think a better question is: why not? It almost seems like this language is destined for greatness.

For one, JavaScript or rather ECMAScript is really a kick-ass language if you look at it objectively. When I say JavaScript most people automatically think about the client-side, browser dependent, inconsistent scripting language which only works half of the time. But this is not really the fault of the language but inconsistent implementation of the DOM model across different browsers.

Internally the language is really consistent, flexible, readable and fun to use. Not only does it have most of the cool features that are all the rage now (ducktyping, closures, variadic functions, prototypes, metaprogramming end etc..) but reads a lot like C. The syntax is full of the familiar and lovely brackets and semicolons that we all know and love (or hate) and all the control sequences and language constructs follow the familiar C patterns. Coding in JavaScript is really a lot like coding in Java only 5 times less verbose which is a good thing.

And when it comes to shuffling around HTML or XML data there is no other language that is both so good at it, and so well documented. We have been using it for that purpose decades now and nothing else compares. No other language can be used int the online so effectively and seamlessly.

Also, Javascrip has something that neither Python nor Ruby possess - a real spec. So it is really a good language - a Language with capital L. It is just burdened with a bad stigma of being a browser specific toy language.

This stigma is slowly dissipating as the Web 2.0 craze is raging on. I don’t care who you are right now - if you are doing any web development right now, you have to deal with Javascript whether you want it or not. You can avoid it, you can claim you are server side guy but if you want to be competitive right now your web app needs to use AJAX and if it is, then Javascript is becoming a big internal part of your code base. You can hide behind a framework, and have it generate AJAX code for you the way RoR does, but sooner or later you will have to do something complex and will end up hacking on js files. Whether you love it or hate it - you will be exposed to it at some point.

So your code is now roughly half Javascript and Half something else which is a bit messy, but that’s Web 2.0 for you. Does it have to be that way though? Of course not. You don’t need a dedicated client side language ad another dedicated server side language. You could really do all your scripting on both sides with Javascript. Yes, Server Side Javascript is not a joke or some pipe dream - it is reality. Believe it or not, but there is a lot of development going on in this area - there are tons of projects out there which use JS on the server side.

These projects range from very simple to very complex full featured solutions. For example, mod_js is an Apache module loosely based on Perl’s CGI.pm which implements ECMAScript on the server side. It is astonishingly simple, and compact but also very immature project.

If you want something more robust and mature there is Jaxer - a self contained Java based server which supports server side scripting in Javascript. The whole idea behind this environment is unifying your code base. With Jaxer you can use the very same language to query the database, dynamically rearrange the HTML output, and make asynchronous calls back to the server. Added bonus is that it is bundled with the very popular Aptana IDE (aka. the Eclipse for web designers) which means it is already near ubiquitous.

If you are allergic to Eclipse and it’s forks and you like NetBeans then Phobos is probably what you will want to sink your teeth into. It uses Glassfish server and uses Javascript as it’s default server side language. Same concept, different approach. The project seems to be mature, well supported and have a big community.

Want more? Theres Helma which is a Rails like framework which leverages server side Javascript and Rhino. The whole thing runs in the JVM and uses Jetty as the default, self contained web server - but you can also put it behind Apache or IIS if you want. How come you can go wrong with a combination like that? You get a MVC framework with a self contained server and set of useful tools and utilities that only requires you to have a basic JVM installed. You get to script it with the dynamic and flexible language that requires no compilation, and no SDK. You get the entirety of the Java API at your disposal courtesy of Rhino. Not only that, but you can simply drop in your custom precompiled Java libraries and classes and seamlessly integrate them into your project.

But there is more - recently I spotted another interesting project called Junction. Like Helma it is a Rails like MVC framework that uses Rhino but in addition, it also has a built in support for Google Gears. This means that apps built on the Junction framework get to benefit from the offline persistence features offered by the Google technology.

There is all this development going on out there. It’s not very visible yet - most of it is somewhat behind the scenes. But it’s like that distant rumbling before the storm. You know something big is coming. Just look around.

You want to develop rich client interfaces? There’s XUL and Adobe Air for you - both using Javascript at their core.

You want dynamic web UI framework? There is JQuery, Prototype, Dojo, Google Web Toolkit and YUI just to name few.

Want to use Java API? Use Rhino. Want to tap into the richness of Microsoft CLR and interact with the rest of .NET ecosystem? Theres JScript.NET. You want to do some native scripting on MacOS? There is Javascript OSA.

You want to add oflline persistence to your web applications? You need Google Gears which is also using Javascript.

The language is everywhere. Everything that is new, that is hot and that relates to the web is at least touching or benefiting from it. Every developer will see it, and work with or alongside it sooner or later. It’s ubiquitous.

The pieces are slowly falling in place and setting up the stage for the upcoming explosion. It’s no longer question of whether we will reach that critical mass, but when will it happen. We have the tools, we have the technology, we have the hook and the need (unifying the client and server side under one language) - now we just need to wait for the hype. And for that, we need branding. Steve Yegge talked about this during his Ted talk - we need to re-brand the language to make it more sexy. Everyone thingks that Javascript is a toy language, and ECMA sounds like a some sort of acne prescription so we need a new, cool name. We also have a good reason for re branding - the upcoming release of Javascrip2 standard which brings about many new features to the language such as classes, interfaces, namespaces, packages, destructuring assignments, structs, type declarations and more.

It is a bucket load of new features so why not start fresh, with a new sexy name and identity. I mean look at AJAX - the acronym really means “using the asynchronous calls in Javascript” but if you say it like that, people immediately fall asleep and run away. But AJAX is cool and sexy. Javascript can be to - and I predict it will be, sooner or later.

Let’s talk about Java and keeping the damn kids of the lawn…

Tuesday, February 26th, 2008

I found this gem mixed in with some old Java code of mine. There is nothing inherently wrong with this class by itself and I bet each and every one of you has a copy of exactly the same class somewhere in your Java code base. In fact, you probably have 8 or 10 different versions of this basic abstraction scattered throughout different projects. I know I do - this is just one of them:

/*
 * Created on Apr 15, 2004
 */
 
package io;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
 
/**
 * Creates an easy to use input interface.
 * Abstracts all the stream related operations.
 * 
 * @author Lukasz Grzegorz Maciak
 *
 */
public class Input
{
	private BufferedReader in;
 
	/**
	 * in will read from the Standard.in using BufferedReader.
	 *
	 */
	public Input()
	{
		in = new BufferedReader(
			new InputStreamReader(System.in));
	}
 
	/**
	 * At any time, the input source can be changed to another
	 * BufferedReader. This can be used to read commands
	 * from batch files and etc.
	 * 
	 * @param i a BufferedReader object
	 */
	public void setInput(BufferedReader i)
	{
		in = i;
	}
 
	/**
	 * Restores the input to the default (System.in)
	 *
	 */
	public void restoreDefaultInput()
	{
		in = new BufferedReader(
			new InputStreamReader(System.in));
	}
 
	/**
	 * Reads a line from the input stream. It returns a string so
	 * if you plan on reading numbers or other data types you need
	 * to parse it yourself
	 * 
	 * @return a String representation of that line
	 * @throws IOException if there was an IO error
	 */
	public String readln() throws IOException
	{
		return in.readLine();
	}
}

Why did I write this back in 2004? Because I was sick and tired of plugging the following line in each class that needed to read user input from the console:

BufferedReader in = new BufferedReader(
		new InputStreamReader(System.in));
String foo = in.readLine();

This way I could replace it with a much less verbose version:

Input in = new Input();
String foo = in.readln();

Some input classes used to be more elaborate including parsing logic letting you ask the user specifically for an integer or a float, or something like that. It’s a nice touch but not essential. What we all really needed back then was a simple console input class but Java mysteriously didn’t provide any. I still remember how the instructors would react when we asked how do you do cin in Java. They would wince, scratch their head and say we will cover that next semester, and for now we should just use the keyboard.java class that came with the book.

Actually, no I lied - my Java instructor didn’t wince or scratch his head. He stuck out his tongue, and scratched his chin for a while. The tongue thing was sort of a thermal valve release thing I think - he did that whenever he was asked a difficult question that required some thought. I guess his brain was prone to overheating - or maybe it was just covered with a thick layer of dust due to lack of use. Then after a 3 minutes of intensive processing (I think his brain was clocked at 1Hz tops) he finally responded that he doesn’t know about “sea-ins but it is probably in the book”. Which was really his default answer - I was always curious why it always took him so long to retrieve the “it is in the book” reply. We theorized that his brain had almost no RAM so if you interrupted his train of thought he was pagefaulting and fetching from storage.

But yes, real teachers made us use some kind of custom written version of the class above until we knew enough about streams to write our own. Every book had a different implementation, with different quirks and dependencies. They were all bloated, and buggy and they ended up being hacked and modified and passed around from student to student. It was a mess - and teaching the language was an interesting exercise of hard waving away all the boilerplate code, class declarations and import statements.

It took Sun close to 10 years to finally provide a simple and easy to use console input class. Now, ever since Java 6 came out back in Dec 2006 we can simply do:

String foo = System.console().readLine();

Why was this not part of the language from the get go? It was not some sort of implementation difficulty or backward compatibility problem. The root of the problem was purely philosophical - in Java input was done with streams, and wrapping one or two stream readers around System.in was deemed perfectly acceptable. That is the thing about Java’s design - whenever there was a choice between straightforward, consistent approach and overly verbose and convoluted one, Sun has always picked the later rather than the former. For example, for the longest time the language did not have a printf function. Instead of passing in an argument formated in a specific way, you had to initialize the NimberFormater class then run 3 or 4 methods on that instance before you could print the string again. So the code that now (since 1.5) can be expressed as:

System.out.printf("%10.2f", x);

used to look something like this:

java.text.NumberFormat formatter = 
		java.text.NumberFormat.getNumberInstance(); 
formatter.setMinimumFractionDigits(2); 
String s = formatter.format(x); 
for (int i = s.length(); i < 10; i++) 
	System.out.print(' '); 
System.out.print(s);

Naturally, you could still use NumberFormat if you wanted to. Sometimes it might be more appropriate especially if you are planning to extend it. But in most cases you really do not need to touch it.

Note that printf is not really syntactical sugar - it is abstraction. Same with the console class - it hides some of the implementation details from the programmer for a good reason. The less code you see on the screen, the easier it becomes to understand. While that NumberFormat block above is very straightforward, if you encountered it in some larger project you probably wouldn’t know what it does at a glance. You would have to mentally step through it line by line to actually figure out you are just fiddling with decimal number precision here. Abstraction is not always about hiding the low level stuff - it is sometimes about hiding the high level stuff that is just to long, and unwieldy to read.

Java is inherently verbose - it’s tendency to replace short and sweet syntactical sugar with long class declarations, and multi level initializations combines with it’s hefty dose of boilerplate (that just must be there) and static typing declarations to compound the problem. It is actually not uncommon to see a 5 lines of pseudo code in the comments, that are then implemented in over 60 lines of actual Java.

And there is a high probability that those 60 lines are in fact abstracting some weird Java quirk - something that ought to be done at the language design level. But instead everyone ends up with their own version of some trivial functionality. And each programmer brings his own utils package which contains among other things the tweaked out keyboard.java and their own implementation of printf. It is especially fun when you try to merge two projects and you realize that they both contain 300 lines of code that implement exactly the same thing but differently, and that refactoring this stuff won’t be that easy as each system relies on the funny little quirks of those custom classes that implement rather trivial functionality.

This is why most of us hack in Eclipse instead of vi - because you need an industrial strength tractor to haul these mountains of code. This is probably also one of the reasons why educators pick BlueJay as the introductory Java IDE, which I think is actually a harmful practice.

It seems to me that Java is currently in the process of joining the league of “old folks” languages that people tend to respect, and emulate in certain ways but not actually use or get excited about. C and C++ are permanent members of that club already. Every time someone brings up one of these languages, the senior programmers usually get that nostalgic feeling - remember those silly pointers, and the link errors - these were the times. The junior programmers usually roll their eyes and mutter something about thankfully not having a pleasure to experience the doubtful joy of manual memory management. Java is slowly but surely heading in that direction.

Java? Heh, I used to use it all the time. I remember that my hello world program was like 7 pages long. It used to make you feel productive - at the end of the day you would realize you wrote few hundred lines of code that don’t really do anything yet - they just need to be there.

Yup… We are getting there. This is one of the reasons why when I was asked to develop web applications I immediately attached myself to PHP. Ruby was not around back then so my choice was essentially between JSP, ASP (booo Microsoft) and PHP. PHP is not very elegant, or very structured. It really takes after it’s cousin perl in that it looks like shit, but gets the job done. And this is what I needed. I needed to build applications quickly, and be able to adapt them to the the constantly changing specs, not spend time modeling, initializing static types and writing essays in code. PHP was language that allowed me to do stuff without much of a hassle.

Note that this was years ago when I was still an impressionable young Java guy. I totally loved the language - and I had a blast designing and modeling my code. I always had this impeccable class hierarchy, organized in packages, all with javadoc comments. It was great - most of the programming assignments were absolutely trivial to me (especially when I was undergrad) so I would amuse myself by beautifying my code, adding functionality it didn’t need and etc. Each of my projects was essentially a thick novel sized stack of papers and my peers would look at me in horror and dismay. I loved it. But to actually do work in Java? Even back then, I decided that to be productive and effective I needed something else.

Java has changed since then - but not a lot. In fact there seems to be a very strong opposition to change in the Java camp. Hell, we wouldn’t have generics, un-boxing and the foreach loop if it wasn’t for C#. The Java ripoff from Microsoft has somehow became a thorn in the side of the Java developers to the point where it motivated them to add features and niceties we were asking for for years. So things are slowly improving. We might even get closures in the next release. Or not - it might be to radical of a step for them. Maybe we will never get them. Then there is a question if we really need them? Why would I even want to wait for Java to implement closures. If I needed them, I could always code in Javascript, and then compile it into Java compatibile bytecode using rhino.

In other words, I can route around Java limitations and verbosity by using another JVM compatible language. This is why we have scala, and jruby and jython and groovy and bunch of other things like that. The java platform slowly growing into a language agnostic platform of it’s own whether sun wants it or not.

Java is no longer the new, cool or hip thing it was when I was starting college. Back then it was huge improvement over C++. It really made our lives easier, and let us be more productive. It was always a hulking behemoth, but we hardly noticed by then because C was a beast that had tormented us for years on its own. But we have moved past that. No one is excited about Java anymore. When I say Java, I see people rolling their eyes and wincing the same way we rolled our eyes and winced when listening about C++.

Java is now entering that “older, wiser and more mature but totally uncool” status. It is not getting retired yet - it’s definitely not senile, and surely not ready for the old-folks home. It’s just getting to that point in it’s life when it starts to tuck in it’s shirt, pull up it’s pants all the way up past the waistline, and has a suddenly discovers some deep seethed desire to keep the damn kids of it’s lawn.

And it seems that no matter how many features they add Java will be still overly verbose, still statically typed and still huge and unwieldy. Naturally, no one is going to drop support for it anytime soon. But given a choice people will be making the same judgment call as I did few years ago and will jump ship. But nowadays they don’t really have to jump far. They don’t even need to leave the Java ecosystem. All they have to do is to switch to one of the other JVM based languages.

First, we have Rhino and Javascript which Steve Yegge predicts to be the Next Big Language. It already has closures, it is dynamically typed, and much more expressive and readable than Java. And yet it lets you leverage the power of the whole Java API. In fact it is fully bytecode compatibile with Java which means you can easily mix and match pure Java and Rhino classes. In fact, once you compile it, there is virtually no difference between the two. Granted, people are not flocking to this one yet but that’s probably because of the “Javascript is for the web” stigma. But with some clever branding we could really get some momentum behind this one.

Ten there is Scala which I keep hearing about. It’s gaining momentum really fast and hype is building up. I really haven’t used it for anything so I can’t say much about it. The website claims it can tap into the .NET CLR libraries in addition to being bytecode compatible with Java which seems to be quite impressive.

We also have stuff like JRuby and Jython which are bound to gain prominence as the youngsters who grew hacking in Ruby and Python get absorbed by the huge Java infrastructures working in the business world. The point is that we can write Java without actually writing Java if we wanted to.

Lately I have been working almost exclusively in PHP, Python and Javascript. I’m also messing around with Ruby and Lisp on the side. Last time I have touched Java was when I wrote code for my thesis and i haven’t touched it since then. It just doesn’t seem as much fun as it used to be. Perhaps I have changed and I’m no longer content just modeling stuff and writing novel sized applications witch don’t really do all that much. It is still my primary language - one that I probably understand the best. But as I’m picking up new projects, and doing new things, time and time again I choose not to use Java as there are always more flexible and exciting tools for the job at hand.

Simple Metaprogramming With Javascript

Tuesday, January 15th, 2008

The more I’m messing around with Rhino the more I like it and in the process I’m learning more nifty Javascript tricks to use on my web based projects. For example, did you know that Javascript has features that facilitate quite effective metaprogramming? Let me give you a short example. Try this in your rhino console:

js> foo = "bar";
js> function bar() { print("baz"); }
js> this["foo"];
bar
js> this[foo]();
baz

In Javascript, fields and functions are implemented as associative arrays. In the example above, this returns rhino’s global object. All the functions and variables defined out of context of an object belong to it. Note how I can access the foo variable by using a string. I can use a simillar notation to call a function as well.

This means we can dynamically decide which function and/or variable is to be accessed at runtime using a very simple syntax without falling back on things like reflection or the Javascript eval() function. This works exactly the same when working within a browser - the only difference is that the top level element is called window.

To put this in context, let’s consider we have bunch of HTML elements on the page. each of them is supposed to trigger a slightly different action. We could naturally create a separate function for each, and then attach an appropriate onClick attribute to each. But perhaps a slightly cleaner method would be to use a single fuction for all of them. You could use something like:

onClick="return process_click(this);"

Then we can construct this function like so:

function process_click(elem)
{
	window[elem.name + "_action"](elem.value);
}

This way, every element will cause a function named with it’s name attributed and _action suffix, and take the value as the attribute. A single line let us build a rather concise, and easily extendable setup. For example checkbox named foo will invoke function foo_action().

Not only are we accomplishing a complex functionality with minimal work we are also enforcing consistent naming convention for the functions. If we manually pended the onClick function on each clickable HTML element we could vary the names significantly.

Now let’s say we need to store the output of this function in some text box on the page. That box can be part of a form called myform and it’s name could be the element name with a prefix of _calculated.

function process_click(elem)
{
	document.myform["calculated_" + elem.name].value = [elem.name + "_action"](elem.value);
}

You can create generic functions which manipulate different sets of variables and/or other functions based on the input values with minimum of code and effort. Sky is the limit here. )

Yes, this is probably a tad contrived example. I don’t claim to be a Javascript expert. In fact this is one of those little hidden nuggets of knowledge that I uncovered very recently after I started messing around with the language. In the past I treated it mostly as a client-side, dumbed down version of Java that is mostly useful for making eye-candy fluffy client side stuff, and asynchronous calls to the server. That’s what I thought, and that’s how I used it. Now I’m begging to see that it is really a powerful dynamic language almost on par with Ruby or Python when it comes to expressibility and feature set.

Rhino framework actually makes it a viable language in and off itself, not mentioning giving you an awesome interactive console you can use for testing and debugging. I really can’t believe I had this really powerful language within my grasp all this time, and never really realized it.

Rhino - Scripting Java with Javascript

Tuesday, January 8th, 2008

After reading Steve Yegge’s Code’s Worst Enemy post I finally decided to give Rhino a whirl. I heard it mentioned here and there for a while now - mostly by Steve actually, but also by others. Actually others were mostly saying something among the lines “WTF is this Rhino shit Steve is talking about?”.

In fact a while ago I went to check it out. I saw the homepage and my thought process went something like this:

  1. oh, mozilla - this must be cool
  2. lol rhino picture
  3. it does what with Javascript?
  4. Javascript? With Java? WTF?
  5. allright, fuck it - I don’t have time for this crap right now

Now I went back, and decided this might be one of the most awesome things I have seen lately. To make the long story short, Rhino lets you write Javascript scripts that can leverage the Java API and will run on the JVM.

But isn’t Javascript, for making AJAX websites? Yes it is, but it is also a very nice scripting language. It has most of the nifty dynamic features of dynamic languages such as Ruby and Python (like ducktyping for example) and a familiar Java like syntax with braces, semicolons and etc. What can Rhino do for you?

First, it provides you with an interactive shell that uses Javascript syntax. I know that BeanShell gives you a similar functionality, but Rhino let’s you tap into Javascript specific language features and structures which are not present in BeanShell (at least as far as I know).

Second, it gives you a compiler you can use to turn your rhino js scripts into class files. So you can easily knock out bunch of scripts, compile them, and then stick them in your Java project and no one will ever know. Furthermore your Javascript code will benefit from JIT compilation and other VM goodies.

Finally, rhino lets you load a javascript at runtime, interpret it and return the result from within your Java code. Java 6 actually ships with the Rhino interpreter you can invoke at will.

But the overwhelming benefit here is that you get to code in Javascript. In other words, you get a language that is less verbose, more flexible and more dynamic than Java, which can do everything that Java does, and which integrates seamlessly with your Java code. Just read Steve’s post and you will see the point just as I did. Java verbosity does impair readability of code and Rhino is the solution and the cure.

To drive the point home, let’s do a “Hello World” example. First, in Java:

public class Hello
{
	public static void main(String[] args)
	{
 		System.out.println("Hello World!");
	}
}

Have you ever tried teaching Java? You show people this example, and first thing you say is this:

“Don’t worry about the public class thing. We will talk about classes later, for now just keep in mind that this line has to be there. Consider it a standard boilerplate code.”

Then you do even more hand waving, telling people not to worry about static, or the String[] args bit and etc… Of course we, advanced programmer peoples know what this stuff means. But think about it - how much fucking code do you need to write just to run few simple tests.

Now let’s do the same thing Javascript under Rhino:

print("Hello World!");

The effect is exactly the same, but simplicity and readability of the code is incomparably better. What we are talking about here is a drastic reduction in the amount of the boilerplate code you need to write. You can also skip variable declarations, generics, casting and etc. So not only is your code becoming easier to read, but also easier and faster to write. This is just a silly example. You can do much more, for example check out this little gem taken directly out of the Rhino documentation:

t = java.lang.Thread(function () { print("Hi There!"); });
t.start()

I just extended the Thread class, implemented it’s run method, instantiated it and launched a thread in mere two lines. You can’t do this in Java! This is the kind of dynamic programming we are talking about. Actually, I don’t think you can do something like that in BeanShell either I might be wrong. Even if I am, Rhino outperforms BeanShell considerably in many cases.

Note that I can use the compiler that ships with Rhino to compile any of the scripts above into a .class file just as I would with an ordinary Java file. How to do this? Firs let’s talk about getting rhino set up. On my Ubuntu box I can install rhino simply by doing:

sudo aptitude install rhino

This will put a a wrapper for the interactive shell as an executable script under /usr/bin/rhino as well as the rhino jar file in /usr/share/java/js.jar. You may want to manually add this last path to your $CLASSPATH variable. This was not done for me upon installation, but then again I’m using dapper repositories so your millage may vary. If you are just planning to use the shell, this is all you will need to do.

Let’s say we named our hello world script hello.js. To run it using the rhino shell just do:

rhino hello.js

Yes, you have to explicitly call rhino. The #! thing doesn’t work - I tried it. One of my professors used to call this a “sheebang” but that reminds me of that stupid Ricky Martin song which makes it distinctively un-geeky in my mind. So I refuse to use that term. Instead I shall refer to it as “Octothrope - Exclamation Mark Junction” or something like that. I suspect it doesn’t work because /usr/bin/rhino is just a shell script that runs the shell from js.jar - not a true shell or interpreter in itself.

Unfortunately the package author didn’t provide a similar script wrapper for the compiler so you have to run it manually by evoking the appropriate method from js.jar. If you added the js.jar to your classpath, then it’s easy. The following command should generate hello.class file for you:

java org.mozilla.javascript.tools.jsc.Main hello.js

I recommend creating a wrapper script containing that line and sticking it somewhere in your path for quick access in the future. You can look at the /usr/bin/rhino scrip, and then just add the appropriate class name to it.

Once you compile your js file, you should be able to run it just like any other java class with one small caveat - it now depends on js.jar so you may need to package and ship it with your code and always include it in classpath.

On windows you will need to do everything manually since all you really get in the downloadable package from Mozilla is the jar file. Thus you will need to create the wrappers yourself. For example you can do something like this for the shell:

@java -classpath ".;C:\path\to\js.jar" org.mozilla.javascript.tools.shell.Main %1

Call it rhino.cmd or something. Then do this for the compiler:

@java -classpath ".;C:\path\to\js.jar" org.mozilla.javascript.tools.jsc.Main %1

Then just remember to include js.jar in your classpath, or put it in the environment variable.

What would you use this for? Tons of things. For example - unit tests. You can still use JUnit and shit, but now instead of a hundred lines you can set everything up in 30. Actually any kind of testing could be done with rhino. That and quick prototyping, and mock-ups. You really can code faster and think clearer when you don’t have to worry about all that boilerplate code. And hey, Steve is rewriting his whole MMO in Rhino - he thinks this is actually a better language for large projects than Java. And that’s good enough endorsement for me.

Now if I could just figure out how to make Eclipse to do that “compile as you type” shit for rhino scripts I would be a happy man. I bet there is a plugin that does this somewhere - I just need to find it. )

Java: Swing or SWT - which one is better?

Saturday, June 30th, 2007

I’m actually to lazy to write a full argument here, so I will just post my bullshit filler crap from a recent research paper:

5.3 Designing a Graphical User Interface

The discussion of GUI design should start by choosing appropriate widget toolkit. Java offers developers several attractive graphical environments. We will first take a closer look on each of them. Visualization details will then be explained in terms of that chosen toolkit.

5.3.1 Choosing a Widget Toolkit

There are three competing major widget toolkits that can be used for building graphical user interfaces in Java: AWT, Swing and SWT. Both AWT and Swing are currently included in Java Standard Edition, while SWT is an external set of libraries that needs to be downloaded and deployed separately.

The AWT toolkit was the first widget system implemented for Java. It is composed from fairly simple wrapper classes which in turn make calls to the native windowing environment to display GUI elements. Since each platform has a different set of native widgets, Sun only included the most basic ones in AWT [37].

Swing toolkit was developed in 1998 as a replacement of AWT. It abandoned the idea of using the systems native windowing environment, and designed a complete, feature rich widget toolkit entirely in Java. Swing is still in active development, and offers an impressing number of different graphical tools and GUI elements to the developers. For example, the package included in Java 1.4 includes 85 public interfaces, and 451 public classes [40].

The pure Java implementation however has proved to be both a blessing and a curse for this toolkit. Since Swing elements are really Java objects, they can only communicate with the underlying operating system through the JVM. In some cases this can create significant overhead, and thus Java based interfaces will often appear
to be less responsive, or slower than their native counterparts [37].

The Standard Widget Toolkit (SWT) [41] developed by IBM is a hybrid between Swing and AWT. It combines both approaches by including both calls to native widget elements, as well as implementing pure Java based ones. This helps to significantly improve the performance without sacrificing any of the advanced features one may
look for in an enterprise grade product [37].

The difference in performance, and responsiveness between Swing and SWT however is widely disputed and highly controversial. For example some benchmarks claim that Swing can outperform it’s competitor with respect to speed of rendering and re drawing windows on non-windows platforms [42]. Thus is is not very clear if SWT is really faster than Swing, or if overhead of the native calls and communication between Java and non-Java elements diminishes any performance gains stemming from using a native widget implementation.

Benchmarking the two toolkits is out of scope for this paper, and thus we chose Swing as our GUI toolkit because it is a Java standard, and it reduces the complexity of our code by eliminating dependency on a third party library.

Bibliography

[37] S. Holzner, Eclipse: Programming Java Applications. O’Reilly, 2004.
[40] R. Eckstein, J. Elliott, B. Cole, D. Wood, and M. Loy, Java Swing. O’Reilly, 2002.
[41] “The standard widget toolkit,” IBM. [Online]. Available: http://eclipse.org/swt
[42] I. Kriznar, “Swt vs. swing performance comparison,” Cosylab D.O.O, 2005. [Online]. Available Here

© 2007 Lukasz Grzegorz Maciak

I pulled the above from a draft version because it’s late, and I don’t feel like locating the finalized reviewed document. So there might be typos and grammar errors in there - which is of course nothing new around ere.

I ended up using Swing, and perhaps it was not the best choice. Not for an image processing application perhaps. So you tell me. Which one is better in your experience. Is SWK really that much faster than Swing? Is the added speed worth the hassle of bundling it with correct SWK packages for correct systems?

I would love to hear from bit SWK supporters - what are the best selling points of this widget kit over Swing, other than the speed? Anyone knows any good benchmark tests that were done to compare these?

I will have to make this same decision for another project soon, and as usual I’m not entirely convinced which one to choose. I’m leaning towards Swing because I worked with it before, and I know at least some of it’s quirks and pitfalls to be avoided. SWK would be a completely new ballgame.

What do you think?