Wednesday, August 31, 2011

New guy in town: knockout.js

Today we're going to take client-side JavaScript to a whole new level with the MVVM pattern using knockout.js.

The "why"


Imagine you're writing an application using, let's say, WPF or Silverlight. What's nice is that you have a clean separation of concerns between what's being displayed in terms of the layout (which is in fact the first V in MVVM) and some object backing up that view (which is the VM in MVVM in this case). This allows the application to be extensible and well structured.
Granted you can make a mess everywhere and MVVM architecture is no exception. You still have to use your brain while coding :)
Up until recently there has been no framework giving you the opportunity to have that kind of clear separation in JavaScript. Granted there have been tools like ExtJS and jQuery to help you out with modern UI elements like calendars and grids as well as low-level operations on DOM and events but there has been nothing so far that'd help you out write in a clear MVVM declarative style. Now there is!

The "what"


That's quite simple: the mini framework is called knockout.js and implements the MVVM pattern in pure JavaScript and DOM (not necessarily HTML but that'll work for DOM creation as well).

The "how"


Well, here's the good part, which will be extremely easy:

<html>

<head>
<title>Example</title>
<script 
type="text/javascript" 
src="https://github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js">
</script>
<script 
type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
var viewModel = {
data: ko.observable("Hello, world!")
};

ko.applyBindings(viewModel);
});
</script>
</head>

<body>
<p>The current value of data is <span data-bind="text: data"></span></p>
<p><input type="text" data-bind="value: data"/></p>
</body>

</html>
See how there's no "Apply changes" button? This is because once you've entered the text into the input box it'll be automatically transferred to the viewModel object and since that's an observable it'll notify all subscribers about the fact that the value has changed and the text on the page gets updated automagically.

Going fancy


I'd like to see some fancy stuff in here like responding to button events and the like. Let's see how we can do that with KO:

<html>

<head>
<title>Example</title>
<script 
type="text/javascript" 
src="https://github.com/downloads/SteveSanderson/knockout/knockout-1.2.1.js">
</script>
<script 
type="text/javascript" 
src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
var viewModel = {
data: ko.observable("Hello, world!"),
show: function() {
alert("Current value is: " + viewModel.data());
}
};

ko.applyBindings(viewModel);
});
</script>
</head>

<body>
<p>The current value of data is <span data-bind="text: data"></span></p>
<p><input type="text" data-bind="value: data"/></p>
<p><button data-bind="click: show">Click me</button>
</body>

</html>
Again, the same page but with 2 additions:
1. A callback function called show as part of the viewModel
2. Declarative binding of the above function to a button using the last data-bind. Cute, isn't it?

I know that I'll put it to some good use in my next project. Just for the heck of it :) I like the idea that it is completely cross-platform and yet so incredibly easy to use!

Tuesday, August 30, 2011

JSF 2.0 - Is it really better?

I know most of you will hate me for the post I'm writing but I have no choice. I really need to stigmatize the framework and make clear to anybody still using it that they have been lost in the woods. Literally...

Like you (as the reader of my blog) already know I hate JSF. I hate it so much that I've dedicated an entire blog and site to bitch about what a pain in the ass it is to use. Being the enlightened man I am from time to time I like to come back to stuff I hate to make sure they didn't do anything stupid like making the framework usable or so. This time was no different.

So I did it. I've installed NetBeans (I usually use the Far Manager's build-in editor but for this exercise I've decided to go crazy a bit and use the full-blown IDE supported by JSF's creators). I've followed the standard File -> New procedure, selected some JSF JPA CRUD example (because I couldn't find anything simple on the net) and started reviewing the app.

First thing that hit me was the really cruel style of the web UI the application presents. In one word "HORRIBLE". Not that it ain't usable - God forbid - but plain "usable" these days just will not cut it. So the GUI is butt ugly - how about the code?

Now that's the place I like JSF most for: the code was just exemplary bloated :D Let me give you some bottom line figures:

1. It's a pure CRUD application. Absolutely nothing fancy. No Ajax or the like cool features whatsoever.
2. It's an application that manages 7 entities (customer, discount code, manufacturer, micro market, product code, product and purchase order).
3. Everything that was generated is 706068 bytes in 72 files!!!

Now compare this to, let's say, Rails, Grails or Sinatra + Data Mapper is about 8 times bigger. I know it is an enterprise sort of thing and that it's not meant for mare mortals. It's the enterprise kind of solution that you'd use at work and not for fun.

Anyways, JSF still sucks, big time. Lot's of hand-written XML, tons of Java code to implement pretty much every aspect of the application (with parts of it having cyclomatic code complexity at the level of 20+). That's just a no-go for new projects that need to deliver solutions on time, on budget and in scope.

One last thing: For crying out loud the web is stateless! Why would anyone force a solution that inherently introduces state which in turn means no scaling possibilities and stupid ideas like "page life cycle" and "control binding"? Why would you ever want to fear JavaScript programming when there are layers of abstraction like Ext JS or jQuery?

I wonder if the MyFaces implementation still differs from the reference one in the way that component libraries will work on one and not the other. I didn't check it out myself - I'm not that brave...

The conclusion is that if you're still doing JSF these days just drop it. Now. It's horrible!

Thursday, August 25, 2011

The Process

I've been working this past few years for a company that utilized Rational tools for issue tracking and source code versioning. Long story short it was a nightmare to use ClearCase and ClearQuest with its stone age web interface was more than annoying but it was to some extent usable.

Nowadays the same workflow is doable using opensource tools like Git and GitHub for anyone. Here's how the process works:

- request a change to the system
- do the changes
- integrate them to the so called main line

Using GitHub it's dead simple:

- file an issue
- clone the repository, do some changes, check them in
- put out a pull request for the maintainer to integrate your changes

All that takes some 2-3 minutes if you know what you're doing and if the test suite you're dealing with is fast enough. Piece of cake.

Now if you'd like know how it looks like using Rational tools (and I mean the good stuff, fully integrated) take a look at the following screen cast.

I hope ClearCase will soon be seen for what it really is: a performance and evolution blocker.

Wednesday, August 10, 2011

Git: publishing a site after push

Today we're going to do an amazing thing: publish a website using Git :) This will be very similar in outcome as the deployment model used by Heroku :) Interested? Read on...

The usual thing is that you have a folder that's exposed on the web and using your favorite web browser you can make the server send you files stored in the folder in question. There's nothing special about that. What's actually very annoying is that every time you do some changes there's a need to upload the new files to the server.

There's been tons of different solutions to that issue ranging from automated synchronization agents to manual ftp operations. The one solution I like most is to use Git to do the heavy lifting for me. Here's how it's done.

You have a repository at, let's say, /srv/git/my-website.git and want to keep the actual files to be served at /var/www. To make git populate the latest versions of your files once you've pushed your changes you need to:

1. Create a file named /srv/git/my-website.git/hooks/post-receive with the following content:
#!/bin/sh
GIT_WORK_TREE=/var/www git checkout -f
2. Set it's permissions so that it is executable
chmod +x /srv/git/my-website.git/hooks/post-receive
3. Set the ownership of /srv/git/my-website.git/hooks/post-receive so that whatever user runs the server process can execute it.

And before I forget: the destination folder needs to already exist and the user that's managing the repository (for example "git" or "apache") needs to have read/write access to that folder!

And that's it! Once you do a git push your changes will be automatically propagated to the proper folder :)

Have fun!

Monday, August 1, 2011

Java 7 and diamond operator

Java 7 has finally been released. After 5 years we've finally been given a new toy to play around with. Better, faster, lighter.. One would hope for a breeze of modern features in the language after reading statements like "Type inference" and so on.

What I'd like to make sure everyone understands is that the so called "Diamond operator", further more specified by Oracle as "Type inference for generic instance creation" is nothing more than a lie sold to us once again. Let me show what I mean.

Java 1.6 code:
List<String> names = new ArrayList<String>();
In this case there's nothing to inference because the code is given to the compiler with all the details. Now what actually happens when the code gets compiled?
The right-hand operand (as well as the left-hand side) is stripped of the generic parameter because of the type erasure, one of the most incredible nonsense in Java. So in fact it's no different that saying
List names = new ArrayList();
In the light of the last statement here's what the creators of Java 1.7 made to ease our pain:
List<String> names = new ArrayList<>();
In this case instead of forcing you to specify both generic arguments they only make you specify it once (where the compiler will actually need it). That's it. The type erasure still takes place so the compiler really couldn't care less about what kind of generic freak show is being assigned to the variable as long as it satisfies the assignment (which in this case has nothing to do with generics but simply with the fact that an ArrayList is a List).

Now let's look at what type inference looks in other languages. Let's start with Groovy:
def names = new ArrayList<String>();
Here we see that the type of the names variable has been inferred to match the type being assigned to it. In Scala the situation is almost identical:
var names = new ArrayList[String]()
Again here's a real type inference in action.
Let's switch platforms for a moment and see how it's done in C#, a statically typed language for .NET:
var names = new List<String>();
What you see here is once again an additional keyword that marks the variable as being subject to type inference.

At the end of the day for me it is more important what the variable name is and that's what exposed in C#, Groovy, Scala and pushed to the background with all the type declaration fuzz in Java.

We can go on and on with examples from other languages where type inference goes beyond the simple fact that you don't need to specify the generic type of the variable twice. There is however one thing that can make you wonder what the hell is actually the type inference in Java style for? Let's see the following example:
List<String> names = new ArrayList<String>();
names.removeRange(0, 1);
This code obviously will not compile but this snippet (in Scala) will:
var names = new ArrayList[String](); 
names.removeRange(0, 1);
Why is that the case? In the Java snippet what we're doing is we're specifically saying that he variable is of type List<String> not ArrayList<String> which in turn means that the method removeRange is not available. In the second example what we're saying is that the variable names should be of type ArrayList[String] because that's what the type inference will ultimatelly figure out. But do we really want to have a List in the Java version? If so why do we specify ArrayList as the class to define the construct that we want to instantiate? Shouldn't we have that instance injected from somewhere else and then code against an interface instead? And if we're instantiating an ArrayList do we really need to strip ourselves from the actual thing that we have oh so obviously specified and play cripples just for the fun of it? Or better yet here's how the Java code could have been written:
List<String> names = ArrayList<String>();
((ArrayList)names).removeRange(0, 1);
Cute, isn't it? And so damn readable!!!

Again we can go on and on with examples and theories what actually is type inference and if what Oracle is feeding us is a trick to make us believe Java is still evolving. To my liking there's no point in coding in pure Java, a language that didn't see a major change for 7 years (September 30, 2004 where generics have been introduced). Or do you think that underscores in integer literals deserve to be taken as a major breakthrough? :D

Have fun!