Wednesday, April 30, 2008

JavaScript On The Wire

I have been working on a website using Phobos, and it is interesting to
note some powerful features that are very subtle when using Phobos and
JavaScript in general compared to some other languages. One of these
features is what I have seen some call JavaScript on the Wire. This
means using JSON to transfer data around in your application. You can
read more about JSON at JSON.org. Now why is this powerful. In
JavaScript, it is powerful because JSON describes objects. Basically,
your data is described as an object, and you can pass it around to
different modules and functions without recreating it or destroying it.

To demonstrate, lets take a html form post. We can post that form to a
controller in Phobos. Inside that controller we can call a Phobos
library function to get our form field values with this line of code:

formFields = library.httpserver.parseRequestParameters();

formFields is now an object containing all of our form fields from our
html form. Let us suppose that we want to pass this on to a data
validation object which we have encapsulated as an object. We can do it
like this:

formFields = module.validateForm(formFields);

Now persist the data to the database with another module we have:

formFields = module.saveFormData(formFields);

Now use the model to pass the obeject back to the view to render the form:

model = formFields;

What we have just demonstrated is that we can take an object from some
input and pass it around all through our cycle of processing always
using the same object. Please do not forget that because we are using
JavaScript, we can add additional properties and methods to that object
anywhere in our cycle as well without affecting anything.

A good rule I have found is use to always pass data using JSON. This
not only makes coding easier, it also allows greater flexibility. If
you write a function which accepts one parameter it will get the job
done. However, if down the road you add a second parameter, now you
have some maintenance to do wherever that function is being called.
With JSON and passing objects, it doesn't matter. Just add a property
to the JSON object and the function doesn't care. It just accepts the
object with the extra property. Every other call to the function is
passing in an object with one less property. This rule makes for
flexible coding and less maintenance and broken code.

I am looking forward to see what will come out of Java One for Phobos,
although I will have to wait for the blogs and media as I am not able to
attend. While mostly using Phobos for web applications, I am interested
to see if Phobos will start up from the command line. Glassfish V3 has
options to run trimmed down, and light weight. If you can run Phobos in
a light weight Glassfish, it will open up some fun possibilities.
Because I do system maintenance, I can think of a few system scripts and
tools that would be nice to write in Phobos.