java – Terminally Incoherent http://www.terminally-incoherent.com/blog I will not fix your computer. Wed, 05 Jan 2022 03:54:09 +0000 en-US hourly 1 https://wordpress.org/?v=4.7.26 Arguments against abstraction http://www.terminally-incoherent.com/blog/2012/01/06/arguments-against-abstraction/ http://www.terminally-incoherent.com/blog/2012/01/06/arguments-against-abstraction/#comments Fri, 06 Jan 2012 15:35:50 +0000 http://www.terminally-incoherent.com/blog/?p=11050 Continue reading ]]> You know what is the nice thing about Google Plus? Lack of that pesky character limit of Twitter. You can post a full essay as a status update if you want to. Not that you should. I try not to do that as a rule because no one wants to read long essays in their stream. And, if I posted essays over there, then I wouldn’t have anything to post on here. It does not mean I’m not tempted though.

Take this post for example.

Initially I wanted to just make a short comment on Bozhidar Bozhanov’s defense of Java verbosity. About 500 words later, I realized it probably should cut the status update short, and expand it into a full blog post.

Bozhanov makes an interesting argument but I believe he mistakenly talks about “verbosity” while his examples clearly show that what he likes about Java is the low level approach to things like I/O or http response handling. His is an argument for explicit complexity rather than verbosity per se.

Java has reputation for verbosity for more than one reason. It is low on syntactic sugar and prefers long chains of method calls over symbols. It is also both statically typed and explicit to a fault leading to long list of type declarations that preface any useful code. Finally Java is low on built in abstraction classes. The general language design philosophy is to be as explicit as possible, unless it actually get in the way (and it does – more on it later).

This focus on explicit way of doing things means that there are often no quick and easy ways to do stuff like I/O or HTTP request handling. You have no choice but to dive deep and understand streams and servlets to do just about anything. It also forces you to re-implement the same solution every single time.

Bozhanov is right – you always start by copy-pasting some boilerplate code. Then you understand the boilerplate code. What he forgets is that you then you continue copy-pasting that code for the rest of your career. Why? Because once you find an optimal way to read your files, handle your http responses and etc, then there is usually no need to change it. It will always be the same block of code – copy-pasted across all your projects. You might as well abstract it into your own class, import it everywhere, and just forget about the whole explicit mess it. Or use a third party class/framework to do abstract it for you.

But then you have more code to test against.

He is essentially the same argument that C programmers make about manual memory management. It’s true that you will probably never fully grasp the fine points of C pointer arithmentic and the subtleties of memory allocation and dealocation. But if you are a Java programmer – or for that matter a programmer in any garbage collected, JIT compiled language you don’t have to. That layer is abstracted, and you can concentrate on solving a problem without being distracted by side problems of memory allocation.

Same with Java. Some of the other languages out there use more abstraction – and for the most part that is a good thing.

Hell, Java does it too. The language has been slowly growing abstractions for common tasks, as a response to the broad and unilateral criticism of it’s needless explicit from within of our industry. Let me give you a quick example.

When I was a young undergraduate and was just starting to learn Java, there was no easy way to read user input from the console. The usual programming language teaching tradition says that the second program students ought to learn after “Hello World” is more or less “Hello Bob” – a version that asks the user for their name and then outputs it. Unlike most languages, Java did not have an easy way to do this back then – you had to fuck around with streams and you had to catch an exception this:

String name;
BufferedReader br;
br = new BufferedReader(new InputStreamReader(System.in));
try 
{ 
   System.out.print("Enter your name: ");
   name = br.readLine(); 
} 
catch (IOException ioe) { }

This is all good and great if you want to teach your students about string buffering and exception handling. But chances are that 90% of the time all you want is to get a string from the console without worrying about all the underlying mechanics.

What happened back then was that every intro to Java book on the market shipped with it’s own “Console” or “KeyboardInput” library on a CD or downloadable from the internet that would abstract all of the above to a single call to a static method.

Eventually, common sense prevailed and these days Java programmers can just do:

Console c = System.console();
String name = c.readLine("Enter your name: ");

Can you still do it the old way? Of course you can. Whenever you really need fine grained control over the way stream is buffered in memory, you can work with streams. The point is, you don’t have to. You have an option not to worry about it and use a tested, mature, built-in abstraction library.

For the sake of the argument, both PHP and Ruby also allow you to fuck around with I/O streams. The author of the blog post was never aware of this, because he never actually needed them, until he stumbled upon Java which forced him to master them. I find this very telling.

The fact that he was able to solve problems, and write functional code without deep understanding of these concepts leads me to believe that this understanding was not crucial. I’m not saying you should not know these things – that knowledge does make you a better programmer. But perhaps it is best to cross that bridge when the problem really necessitates it rather than to be forced to solve it as a prelude to a whole different high level problem.

For example, when your abstractions start leaking it may be time to roll up your sleeves and dive into the sea of complexity. But as long as they hold water well enough for the issue at hand, you really don’t need to worry about them.

Abstraction is useful because it lets you look at the big picture. It lets you fit more of problem-specific code on your screen and in your head. Without them, it is easy to miss a forest for the trees sometimes.

]]>
http://www.terminally-incoherent.com/blog/2012/01/06/arguments-against-abstraction/feed/ 1
Facebook: Upload Failed http://www.terminally-incoherent.com/blog/2009/12/07/facebook-upload-failed/ http://www.terminally-incoherent.com/blog/2009/12/07/facebook-upload-failed/#comments Mon, 07 Dec 2009 15:59:59 +0000 http://www.terminally-incoherent.com/blog/?p=4193 Continue reading ]]> I wrote about reasons for using Facebook some time ago. I won’t repeat these things her. I will merely reiterate that it is a social communication platform. For many people this is the only internet based communication platform that they care to learn how to use. And so, I use it too.

For example, if I wanted to share some pictures with friends and family I could upload them to a proper picture sharing service like Flickr. This way anyone who wanted to snag a full resolution copy could do that at any time. But that route is full of roadblocks.

For one, none of my family members has a Flickr account. Therefore they won’t be able to see my private Halloween gallery. I don’t want to set it to public so I would have to create invitations for everyone involved, send them out in a batch. Then I would have to respond to emails from people who inadvertently locked themselves out, or whose email client mangled the invitation URL. And of course everyone would ask me why I just didn’t upload the pictures to Facebook like a normal person. So yeah… You get the picture here.

Few days ago I was uploading pictures to Facbook waiting for them to be mercilessly squished, compressed and mangled beyond recognition when I got this error:

Facebook Error Message

Facebook Error Message

Funny thing is that this dialog shows up AFTER the upload is complete. So you get to watch a progress bar for 10 minutes before it lets you know if failed to upload and save a single pic. Great!

Initially I thought that this was a Facebook glitch but on a lark I decided to test it in IE8. It worked.

WTF in HELL? This made me really, really angry but after about 5 minutes of nerd raging I realized that a high profile site such as Facebook would not let such an annoying bug to affect their Firefox user base. That stuff just doesn’t happen at that level – outrageous, browser based bugs get stomped really fast because they tend to create a very vocal community uproar and negative coverage in industry press. Or at least that’s what I told myself.

So I started looking more into this issue and identified several failure points:

  1. Facebook image uploader is a Java applet – so it could be Java glitch
  2. My Firefox just upgraded to 3.5.5 so this could be a FF bug
  3. I was using Vista 64 bit which just doesn’t fucking work half the time
  4. All of the above

Some googling led me to believe that this is #4. In fact, it seems to be an issue that dates back to the days when the OS was still called Longhorn. I just never encountered it because I don’t upload pictures to Facebook that often. And it’s not that I choose not to or anything. I just happen not to have a life. So yeah.

Anyways, I found couple of suggestions on how to fix this issue. One suggested to run Firefox as Administrator and try to upload that way once. Allegedly that will allow the Java plugin to re-set it’s registry entries and will work correctly from that point on. That didn’t work either. Still, it’s worth a try if you are experiencing this bug.

I tried upgrading my Java but that didn’t do anything as I already had the most recent release. Eventually I stumbled upon a suggestion which did work:

  • Delete your cookies and Temp files

Yep, it turns out that it is just that simple. I cleaned out the temp files and cookies using the built in FF feature, restarted the browser and the upload feature started working again. Sometimes the simplest solution is the one that works the best even if it seems like the problem is way more complex. Fucking Occam and his fucking razor.

I’m posting this here for future reference and the good of humanity in general.

]]>
http://www.terminally-incoherent.com/blog/2009/12/07/facebook-upload-failed/feed/ 5
Developping Blackberry Apps: Dice Roller http://www.terminally-incoherent.com/blog/2009/10/27/developping-blackberry-apps-dice-roller/ http://www.terminally-incoherent.com/blog/2009/10/27/developping-blackberry-apps-dice-roller/#comments Tue, 27 Oct 2009 14:24:53 +0000 http://www.terminally-incoherent.com/blog/?p=4053 Continue reading ]]> Last week I wrote about developing a simple hello world app for your blackberry. Today I want to go one step further and show you how to make a real world application that actually does something. Of course since we are all learning to use this new API I want to keep it simple, bare bones and straightforward. We can add bells and whistles later.

For now I just wanted to get a handle on using the basic GUI components, and capturing events such as pressing a button. I don’t particularly care how the app will look. I also don’t care about fancy stuff such as detecting the orientation flip in Storm.

What kind of application would fit all these criteria? Simple? Straightforward? No frills? And yet somehow useful. I pondered this for a little while and came up with this: a dice rolling application. You know, something that emulates rolling one or more dice of a certain type. It’s basically a random number generator attached to a GUI front end. And it’s useful too. Well, for me at least. The ability to generate random numbers in your phone comes in handy when you are into pen & paper RPG games like me.

So I drew up a simple design in my mind. The app would essentially have two input fields. One field would accept the number of dice to be rolled, while the other field would accept the type of dice. For those of you who don’t know this: yes, there are many types of dice. The die you usually see in casinos is what we call a d6 – a six sided dice. We role players also use d4, d8, d10, d12 and d20. When needed we also simulate a d100 by rolling two d10’s (you pick one dice to signify the tens and the other the ones).

The user will type in the values into the two fields, press a button and get the results. Simple and easy to develop. The end result should look like this:

Blackberry Dice Roller App

Blackberry Dice Roller App

How do we do this? Let me show it to you. I apologize for the wall of text code segment but the app is just a single class and a fairly short one at that. It really doesn’t make much sense to break this code up. Note that this project uses a driver class just like the one I shown you in the Halo World example. I omitted it here because it is all uninteresting boilerplate code. To actually run this code however, you will need to create one yourself.

import java.util.Random;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.ui.text.NumericTextFilter;


public class DiceScreen extends MainScreen 
{
   private EditField howmany, dice;
	
   public DiceScreen()
   {
		
      super();
      LabelField applicationTitle = 
        new LabelField("Luke's Dice Roller");

      setTitle(applicationTitle);
               
      howmany = 
        new EditField("How Many? ", "2", 10, Field.EDITABLE);

      howmany.setFilter(new NumericTextFilter());
      add(howmany);
                        
      dice = new 
        EditField("What kind of dice? ", "6", 10, 
        Field.EDITABLE);

      dice.setFilter(new NumericTextFilter());
      add(dice);
                
      ButtonField roll = new ButtonField("Roll");
      add(roll);
        
      FieldChangeListener listener = new FieldChangeListener() 
      {
         public void fieldChanged(Field field, int context) 
         {
            int h = Integer.parseInt(howmany.getText());
            int d = Integer.parseInt(dice.getText());
            	
            String result = randomize(h, d);
            Dialog.alert("Results: " + result);  
         }
      };
        
      roll.setChangeListener(listener);
   }
	
   private String randomize(int howmany, int dice)
   {
      String out = "";
      Random generator = new Random();
		
      for(int i=0; i

Very straightforward stuff. The EditField component is basically a combination of a label and input box. Instead of using two components you just do one, and it accepts a string argument that will display some text to the left of the input box. It also accepts the initial value, maximum length and style indicator (in that order).

Each EditField (or rather each Field) defines a setFilter method that lets you pass in a filter object that will prohibit imputing certain values. I'm passing in a NumericTextFilter object which is why the Blackberry Storm displays the numeric keyboard when that field is active.

Finally, I create a listener for my button by defining FieldChangeListener instance as an inner class. I then attach it to my button just like I would do it a Swing application.

I don't think I need to explain the random number generation procedure, since that's something you should already know how to do. If you don't, I recommend cracking open any Java book, or online tutorial. Random number stuff will probably be like on page 3 or something.

To keep things simple, I made the results appear in a modal dialog:

Blackberry Dice Roller in Action!

Blackberry Dice Roller in Action!

It works! Happy dance!

Of course this app has some serious problems. For one, it is ugly as hell. At least compared to most native Storm applications. It is also infuriatingly hard to navigate using the touch screen. You can't really see this in the emulator, but once you load this ting onto your phone, changing fields becomes frustrating. Because they are so close, a downward finger swipe will almost always skip the second field and highlight the button. And upward swipe on he other hand will highlight the first field. Getting to the second field is then a matter of careful finger placement.

This is an usability issue that needs to be resolved before this little simplistic app can be considered worth while. So this is what I want to talk about in the next post in this series. Adding bells and whistles. I want to make this app look pretty, and somehow space the fields out so that they can be easily navigated.

I'd also like to do something fancy - for example remove the button and attach the dice rolling action to the orientation switch event. This way you could actually roll the dice with a flick of your wrist. How awesome would that be? Of course it would require some testing to see how sensitive the device really is, and whether or not the roll would be accidentally t triggered during normal use.

]]> http://www.terminally-incoherent.com/blog/2009/10/27/developping-blackberry-apps-dice-roller/feed/ 1 Developping Blackberry Apps: Hello World http://www.terminally-incoherent.com/blog/2009/10/20/developping-blackberry-apps-hello-world/ http://www.terminally-incoherent.com/blog/2009/10/20/developping-blackberry-apps-hello-world/#comments Tue, 20 Oct 2009 14:41:27 +0000 http://www.terminally-incoherent.com/blog/?p=3957 Continue reading ]]> I almost forgot about this post. It got stuck in the draft queue for a few weeks now, but since I’m running low on postable content, I decided to resurrect it, clean it up and post it.

As promised, I wanted to show you how to create a simple Blackberry application in Java. Of course since this is Java, we will be typing way more than it is logically necessary. For example, a simple Hello World application requires no less than two classes, with a full complement of boring boilerplate code. If you are a long time Java programmer you probably just went “Only two? Phew! I thought it was worse”.

Our first class is basically there just to hold the main function, because that’s what you do in Java. You create a class, then you declare your main function, and then you writhe your procedural code inside:

import net.rim.device.api.ui.UiApplication;

public class HelloWorld extends UiApplication
{
	public HelloWorld()
	{
		pushScreen(new HelloScreen());
	}
	
	public static void main(String[] args)
	{
		HelloWorld instance = new HelloWorld();
		instance.enterEventDispatcher();
	}
}

There are two things here that might require explanation. The pushScreen method takes an UI container as a parameter and then paints it on screen. In our case this container is going to be a class extending net.rim.device.api.ui.container.MainScreen – I will show you how to create one in just a second.

The enterEventDispatcher method enters the main loop and handles capturing and dispatching events. The rest should be self explanatory.

Now for the actual GUI container:

import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.MainScreen;

public class HelloScreen extends MainScreen
{
	public HelloScreen()
	{
		super();
		LabelField applicationTitle = 
			new LabelField("My First Applicaiton");
		setTitle(applicationTitle);
 
		LabelField hello = 
			new LabelField("Hello World!");
		add(hello);
	}
}

As you can see, blackberry apps are built just like any other Java GUI apps. You initialize container, label, field and button objects, you add them to each other creating hierarchies. There are some layout classes that can help you out and if you need to capture events you attach a listener to an object just like you would do it in Swing app. This is how our app looks like in the emulator:

A simple hello world app is not very pretty too look at. Click to embigen.

A simple hello world app is not very pretty too look at. Click to embigen.

It’s simple and kinda ugly, but that’s really all we were going for. It is remarkably easy to create simple, create apps this way. You will however quickly notice that slapping few fields and labels together may work OK for other blackberry models, but is not the best way to make an app for the storm. Because of the way the interface works, it can be sometimes difficult to switch between fields that are very close to each other. Designing usable and good looking Storm apps takes a little practice. But more on that later..

]]>
http://www.terminally-incoherent.com/blog/2009/10/20/developping-blackberry-apps-hello-world/feed/ 5
Developping Blackberry Applications http://www.terminally-incoherent.com/blog/2009/10/01/developping-blackberry-applications/ http://www.terminally-incoherent.com/blog/2009/10/01/developping-blackberry-applications/#comments Thu, 01 Oct 2009 14:36:06 +0000 http://www.terminally-incoherent.com/blog/?p=3850 Continue reading ]]> Few months ago, I got myself a Blackberry Storm. It is a neat little device whose main fault is essentially the fact that it is not an iPhone. It’s essentially a hybrid. On one hand it tries to be more of a fun consumer phone rather than a dull business device and so it eschews some typical Blackberry traits. On the other hand, it is still very much set in the Blackberry way of doing things. So basically the touch screen replaces the keyboard and the track ball, and the main interface is tweaked a bit to be touch friendly but that’s all. In the end result is somewhere in between a traditional blackberry, and a failed iPhone wannabe. Which means that both the people who like the classic Blackberry, and the people who were expecting an iPhone killer are disappointed with the device.

Me, I knew what I was buying ahead of time an I like it. I don’t know, the phone has a certain quirky charm to it, and so far I have been enjoying using it.

So I’ve been a Blackberry user for few months now, and I recently decided that I’m just about done with that end-user bullshit. I mean, I have this device, right? And it has an application building framework and an API out there. I’m a smart guy, so I should be able to figure out how to build apps for this damn thing, no? I mean, how hard can it be?

The answer is, not hard at all. In fact, it’s right up my alley. The Blackberry app development is done in… Tatadada! Java!

Well, fuck me in my sock drawer! That’s right up my alley. Java is my bread and butter ladies and gentlemen. It’s ugly as hell, verbose like a motherfucker, but God damn, I love it!

Not only that – the Blackberry JDE is available as an Eclipse plugin. You know eclipse, right? That’s the IDE that Steve Yegge makes fun all the time. The one that takes 3.5 hours to open up, right? Say what you want about it, but I like it. Yes, me – the Vi guy.

Let me put it this way – writing code in Java is like… Well, like me writing this blog. It’s verbose to the extreme. Every little tiny thing takes 5-6 lines of code. Eclipse will actually writhe half of these for you. And it has kick-as refactoring features which allows you to rename classes and methods at a whim, and see the changes ripple through all the files that reference them. In other words, it helps and makes Java less painful than it usually is.

Btw, did I mention that I am a long time Java developer? I talk trash about it, but only out of love.

So, what does it take to be a Blackberry developer? First you must obtain an outdated version of Eclipse. Yeah, the obsolete one. If you get Galileo the Blackberry JDE plugin will totally hose your installation. Yeah, it will positively demolish, cause it to bug out at start-up and won’t allow you to type anything. There is no un-install feature either, so just don’t install it in your “good” Eclipse folder.

Instead, get a copy of the Ganymede release and unzip it in it’s own folder.

Next, go grab the JDE Plugin. It’s an executable installation package, and it will ask you where is your root eclipse folder. You will then need to point it at your Ganymede directory and let it do it’s thing.

Once it installs, you will see additional menu options, bells and whistles. Quickly pull down the Blackberry menu, would you kindly, and check the “Installed Components” section. As you can see you currently have Blackberry JDE Component Package 4.5.0 in there and nothing else. What you want to have is 4.7.0.

Installed Components (you want 4.7.0)

Installed Components (you want 4.7.0)

Why? Because 4.5.0 is old, that’s why. Ok, you know how I opened this post talking about Blackberry Storm? That’s the one I have, right? So that’s the model I want to emulate when I test my applications. Not some piece of shit curve or world or whatever. So if you want to have the Storm emulator, you need 4.7.0. Or, you know – if you have a different device then you should get the appropriate one. Whatever. The point is, they are all backwards compatible, and you can install bunch of them, and switch them at any time. But it’s a good idea to debug your app in the device you are familiar with.

So, how do you get the 4.7.0 component? Easy – you use the Ecplipse Software Update feature located under the Help menu. Yeah, I know. I don’t get why they put it there either. Help is for manuals, but whatever.

Go to Software Updates, switch to Available Software and click Add Site. Then copy and paste this URL into the box:

http://www.blackberry.com/go/eclipseUpdate

Once it is there, you will be able to see Blackberry Update Site on your list like this:

Blackberry Update Site

Blackberry Update Site

Just drill down, pick 4.7.0 and install it. It may take a while of course. I think the whole package is a little over 100MB so be patient. Once it is done, you will be able to go back to Installed Components and pick it from the list.

When you compile and run your application you will then see this nice little emulator pop up:

The Blackberry Emulator

The Blackberry Emulator

Neat, eh? There is one catch however (there always is, no?). If you happen to be running Vista 64 bit like me, the emulator won’t close. Oh, it will stop working and freeze up but it won’t actually shut down. The only way to switch it off, is to kill it’s process via task manager. Or rather, Process Explorer because the Windows task manager won’t be much help when you don’t know the actual name of the process to kill. It’s fledge.exe btw. I’ll spare you the guessing game.

Actually, after doing this for a while I actually created a little batch script and put it in my quick launch toolbar for closing the damn thing:

taskkill /im fledge.exe

It works fine that way. Annoying and backwards, but it works. And that’s all that matters.

Oh, and the API is here. The docs are fairly clear, though little light on examples. I was able to work with it so far. It’s really not much different from building Swing applications – you’re just using different graphical toolkit here. Stuff like listeners and events works exactly the same.

There is some standard boilerplate code you do have to include in your apps, but it’s actually less than I expected. Next week I’ll show you how to do a simple Hello World app on the blackberry.

]]>
http://www.terminally-incoherent.com/blog/2009/10/01/developping-blackberry-applications/feed/ 2
Clojure: Lisp on the JVM http://www.terminally-incoherent.com/blog/2008/12/01/clojure-lisp-on-the-jvm/ http://www.terminally-incoherent.com/blog/2008/12/01/clojure-lisp-on-the-jvm/#comments Mon, 01 Dec 2008 15:39:26 +0000 http://www.terminally-incoherent.com/blog/2008/11/27/clojure-lisp-on-the-jvm/ Continue reading ]]> I have found a new toy! It is called Clojure. What is it? It is a Lisp dialect that runs on the JVM. Hey, hey, where are you going!

Crap! Around 85% of the readers just left the site in disgust. Some of them have probably un-subscribed from my feed as soon as they saw the word lisp. Oh well, well have to finish this without them.

What’s wrong with Common Lisp you say? Nothing wrong with it. But if you take a language and put it on top of JVM you now have double the amount of power. Here is the thing about programming languages. No matter which one you pick, it will be missing some library or functionality you will need for your project. It’s always a different thing that is missing, but you will never get a language that has everything. And that’s ok. The JVM languages however have the advantage of being able to tap into the incredibly rich Java API, or to seamlessly invoke stuff written in other JVM languages such as Java, Jython, Javascript (with Rhino) and etc..

This gives you a great deal of power and flexibility as you can imagine. This is why I love Rhino which allows me to produce Java compatible code without actually using the Java syntax. Clojure will allow me to do the same thing but with Lisp.

Of course there other JVM implementations of lisp such as Armed Bear Common Lisp (ABCL) or Second Interpreter for Scheme Code (SISC). All of these are fine, but I like Clojure because it seems to be a very progressive project. Instead of simply porting CLISP or Scheme to JVM they decided to create their own flavor, one built from the ground up with Concurrency and Java interop in mind. Traditional lisps don’t do concurrent programming. Since JVM has a great theading support so some of their implementations (like SISC) try to graft it in. But they are bound by backward compatibility and other concerns so the results may vary.

Clojure on the other threads it’s own path, abandoning some traditional conventions and implementing modern ideas. For one it is strongly concurrent, providing interesting abstractions for dealing with synchronous and asynchronous data access problems. Correct me if I’m wrong but I do not thing that any other lisp implementation has such a through and well thought out threading support.

But that’s not all. Clojure natively implements modern data structures such as hash maps and vectors making them behave as functions. Let me show you and example:

(def a (hash-map "foo" "bar" "biz" "bif"))
(a "foo") ; returns 'bar'

The language also extends standard lispy sequence functions such as map and filter to all objects that implement the Java iterable interface. So you can easily apply them to all the crazy custom data structures from your legacy code base. It also supports attaching metadata to your objects. It allows you to associate arbitrary map (eg. hash-map) to an object which does not affect that objects hash for comparison purposes, and doesn’t count as part of that object but which can be accessed at any time from within your code.

There is more stuff there but you can read about it on the Closure homepage. The point is that this feels like a new, vibrant language that is going places. When you work with CLISP or Scheme you are dealing with a mature, and pretty much static language. They are pretty much set in stone at this point, and they are very reluctant of introducing new features.

Clojure on the other hand is in active development, and is constantly being improved. It has a thriving community, a well maintained wiki page and a clearly defined set of goals and philosophy. It is a very exciting project – and one of the very few times, that someone is doing some new and exciting things with Lisp. It is a good idea to keep an eye on it. I’m not saying it will become the next big language. I mean, come on – it’s lisp. But it does take lisp into new and interesting directions which is a good thing and for one I’m excited about it.

If you want to start messing around with it, you will need to do three things:

  1. First download the clojure.jar and put it somewhere
  2. Second download jline.jar and put it in the same directory (if you skip this part you won’t have history, and left/right arrow support in the console interpreter)
  3. Make put this bash script somewhere in your path:
#!/bin/bash 
CLOJURE_DIR=/path/to/clojure
CLOJURE_JAR=$CLOJURE_DIR/clojure.jar
 if [ -z "$1" ]; then 
   java -cp $CLOJURE_DIR/jline.jar:$CLOJURE_JAR jline.ConsoleRunner clojure.lang.Repl    
else
   java -cp $CLOJURE_JAR clojure.lang.Script $1
fi

This will allow you to invoke the command line interpreter by calling your script without any arguments, or run a script provided on the command line. That’s all you really need to get started. Or you can just run it from the command line but as with many of these JVM language things these invocations tend to get way to long to type them in by hand each time.

So if you are a Lisp person, or you are interested in learning some lisp go and check it out. You don’t need to install anything. Just download few files, put them in a temporary diectory and start plugging away. If you don’t like it, delete them and your done. How easy is that?

]]>
http://www.terminally-incoherent.com/blog/2008/12/01/clojure-lisp-on-the-jvm/feed/ 4
Javascript will be the Next Big Language http://www.terminally-incoherent.com/blog/2008/04/23/javascript-will-be-the-next-big-language/ http://www.terminally-incoherent.com/blog/2008/04/23/javascript-will-be-the-next-big-language/#comments Wed, 23 Apr 2008 15:20:29 +0000 http://www.terminally-incoherent.com/blog/2008/04/23/javascript-will-be-the-next-big-language/ Continue reading ]]> 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.

[tags]javascript, ecmascript, rhino, scripting, helma, jaxer, junction, sever side javascript, mod_js[/tags]

]]>
http://www.terminally-incoherent.com/blog/2008/04/23/javascript-will-be-the-next-big-language/feed/ 41
Let’s talk about Java and keeping the damn kids of the lawn… http://www.terminally-incoherent.com/blog/2008/02/26/lets-talk-about-java-and-keeping-the-damn-kids-of-the-lawn/ http://www.terminally-incoherent.com/blog/2008/02/26/lets-talk-about-java-and-keeping-the-damn-kids-of-the-lawn/#comments Tue, 26 Feb 2008 16:06:22 +0000 http://www.terminally-incoherent.com/blog/2008/02/26/lets-talk-about-java-and-keeping-the-damn-kids-of-the-lawn/ Continue reading ]]> 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.

[tags]java, jvm, javascript, scala, jruby, jython, programming[/tags]

]]>
http://www.terminally-incoherent.com/blog/2008/02/26/lets-talk-about-java-and-keeping-the-damn-kids-of-the-lawn/feed/ 2
Simple Metaprogramming With Javascript http://www.terminally-incoherent.com/blog/2008/01/15/simple-metaprogramming-with-javascript/ http://www.terminally-incoherent.com/blog/2008/01/15/simple-metaprogramming-with-javascript/#comments Tue, 15 Jan 2008 16:30:44 +0000 http://www.terminally-incoherent.com/blog/2008/01/15/simple-metaprogramming-with-javascript/ Continue reading ]]> 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.

[tags]metaprogramming, javascript, rhino, java[/tags]

]]>
http://www.terminally-incoherent.com/blog/2008/01/15/simple-metaprogramming-with-javascript/feed/ 4
Rhino – Scripting Java with Javascript http://www.terminally-incoherent.com/blog/2008/01/08/rhino-scripting-java-with-javascript/ http://www.terminally-incoherent.com/blog/2008/01/08/rhino-scripting-java-with-javascript/#comments Tue, 08 Jan 2008 16:50:21 +0000 http://www.terminally-incoherent.com/blog/2008/01/08/rhino-scripting-java-with-javascript/ Continue reading ]]> 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. :)

[tags]rhino, java, mozilla, mozilla rhino, javascript, programming, steve yegge[/tags]

]]>
http://www.terminally-incoherent.com/blog/2008/01/08/rhino-scripting-java-with-javascript/feed/ 7