Monthly Archives: November 2012

JS Routing: Sammy vs. Flatiron Director

Having little knowledge about client-side routing in JavaScript, I decided to compare two frameworks: Sammy.js and Flatiron Director.


I’ll do the comparison on a very simple application (loosely based on a sample from Flatiron). The features I’d like to use are:

  • Routing: Routing based on hash URLs like app#/author.
  • Routing with params: Getting parameters from URLs like “15” from app#/books/15.
  • Multiple bindings: Performing more than one action for a route (in a real app it could be routing and loading some data).
  • Default routes: Plugging in a “default” route for all unmatched paths.
  • Listeners: Plugging in a listener – some special action to execute in addition to routing on all paths.


Flatiron Director

<!DOCTYPE html>
    <meta charset="utf-8">
    <title>Flatiron Director Sample</title>
    <script src=""></script>
    var author = function () { console.log("author"); };
    var books = function () { console.log("books"); };
    var viewBook = function(bookId) { 
      console.log("viewBook: bookId is populated: " + bookId); 
    var wildcard = function(route) { 
      console.log("Wildcard at: " + route);
    var listener = function() { 
      console.log("Listener at: " + window.location); 

    var routes = {
      '/author': author,
      '/books': [books, function() { console.log("An inline route handler."); }],
      '/books/view/:bookId': viewBook,
      '/:def': wildcard

    var router = Router(routes);
    router.configure({ on: listener });
      <li><a href="#/author">#/author</a></li>
      <li><a href="#/books">#/books</a></li>
      <li><a href="#/books/view/1">#/books/view/1</a></li>
      <li><a href="#/other">#/other</a></li>


<!DOCTYPE html>
    <meta charset="utf-8">
    <title>Sammy Sample</title>
    <script src=""></script>
    <script src=""></script>
    $(function() {
      var author = function () { console.log("author"); };
      var books = function () { console.log("books"); };
      var viewBook = function(bookId) { 
        console.log("viewBook: bookId is populated: " + bookId); 
      var wildcard = function() { 
        console.log("Wildcard at: " + this.params['route']);
      var listener = function() { 
        console.log("Listener at: " + this.params['path']);

      $.sammy("#main", function() {
        this.get('#author', author);
        this.get('#books', books);
        this.get('#books/view/:id', function() {
          console.log("An inline route handler.");
        this.get('#:route', wildcard);
        this.bind('run-route', listener);
  <body id="main">
      <li><a href="#author">#author</a></li>
      <li><a href="#books">#books</a></li>
      <li><a href="#books/view/1">#books/view/1</a></li>
      <li><a href="#other">#other</a></li>


So what do I think about them?

Director seems to be fairly lightweight and simple. It has no dependencies and weighs 3.7 kB. It’s almost functional programming (except for the moment when you turn it on) – you can immediately see what’s going on and what the options are.

In comparison, Sammy.js is much heavier. It depends on jQuery (32.7 kB) and it weighs 6.5 kB. It makes more assumptions: Your code needs to run after page is loaded (that’s why it’s wrapped in $.ready here). It makes you write OO code – functions have no arguments, but you get more information exposed on this.

Director supports plugging in multiple handlers to a route out of the box (you can pass an array of functions). In Sammy apparently you need to wrap them in another function.

For some reason Director seems to require URLs to have a slash, like app#/books – never app#books. Sammy does not care.

The rest you can see for yourself in the code above.


Sammy makes me download more code, all the time I need to read documentation (“So what parameters are available here?”, “What does this object hide?”), and in the end it even makes me write more code. Look at the parameterized viewBook handler: With Director, I can add the parameter to handler function and it just works. With Sammy I need to get it from this.

At this point I have strong preference for the Director. It’s smaller and much easier to use. I like that even more because I can directly use it from ClojureScript with minimal friction. It would take quite an effort to integrate Sammy.

Using Angular.js with ClojureScript

When I wrote my last post on ClojureScript, I was really hoping someone would jump in and say: “You’re doing it wrong! Here’s how.”

I did get some interesting replies, especially on HackerNews (where that post was briefly on the front page). There really seem to be two camps here: Newbies as confused as I am, and pros who say you just have to invest the time and learn, then you may be able to make good use of some of existing JS frameworks or (better?) roll your own ClojureScript frameworks. They say it’s worth it once your codebase is big enough.

Getting Angular to Work

Anyway, Greg Weber here on my blog noted that you can actually use Angular with Closure – just need to use explicit dependency injection. So far Angular seemed to require the least work with CLJS, so I was happy to give it another shot. I also found this note on minification in Angular docs very helpful.

In the end I’ve successfully rewritten the “todo” sample application. Here’s one way to do it:

(defn add-todo [scope]
  (fn []
    (.push (.-todos scope) (js-obj "text" (.-todoText scope) "done" false))
    (aset scope "todoText" "")))

(defn remaining [scope]
  (fn [] 
    (count (filter #(not (.-done %)) (.-todos scope)))))

(defn archive [scope]
  (fn []
    (let [arr (into-array (filter #(not (.-done %)) (.-todos scope)))]
      (aset scope "todos" arr  ))))

(defn CTodoCtrl [$scope]
  (def $scope.todos (array (js-obj "text" "learn angular" "done" true)))
  (def $scope.addTodo (add-todo $scope))

  (def $scope.remaining (remaining $scope))

  (def $scope.archive (archive $scope))) 

(def TodoCtrl

The last 4 lines are equivalent of using this array syntax in JavaScript:

TodoCtrl = ['$scope', CTodoCtrl];

Another way to do it is setting the $inject property, like this:

(def TodoCtrl CTodoCtrl)
(aset TodoCtrl "$inject" (array "$scope"))

As usually, complete working project can be found at my GitHub repository.

Implementation Details

Function definition

In the above example I’m defining functions on CTodoCtrl by using “factory functions”. I find this slightly more readable, but it also can be done with in-place definitions like this:

(aset $scope "remaining" 
        (fn []
          (count (filter #(not (.-done %)) (.-todos $scope)))))

Unfortunately, I was unable to get it to work with anonymous functions (it compiled to CTodoCtrl.remaining = (function CTodoCtrl.remaining() {...):

(aset $scope "remaining" #(...))

This did not work either (I wish it did!):

(defn $scope.remaining [] (...))

Objects, Arrays

I’m not quite happy with the use of objects here – I would definitely prefer to use Clojure maps like this:

; Instead of:
; (def $scope.todos (array (js-obj "text" "learn angular" "done" true)))
; Do:
(def $scope.todos [{:text "learn angular" :done true}])
; Insetad of:
; (into-array (filter #(not (.-done %)) (.-todos scope)))
; Do:
(filter #(not (:done %)) (:todos scope))

Unfortunately, it seems Angular doesn’t like ClojureScript types and vice versa. Looks like a small, fixable annoyance.


It’s still ugly at places and not quite spectacular, but I like using functional programming with ClojureScript instead of JavaScript loops.

I mean replacing this:

var count = 0;
angular.forEach($scope.todos, function(todo) {
  count += todo.done ? 0 : 1;
return count;


(count (filter #(not (.-done %)) (.-todos scope)))

And this:

var oldTodos = $scope.todos;
$scope.todos = [];
angular.forEach(oldTodos, function(todo) {
  if (!todo.done) $scope.todos.push(todo);


(let [arr (into-array (filter #(not (.-done %)) (.-todos scope)))]
      (aset scope "todos" arr))


All in all, I may finally be seeing the light at the end of the tunnel. Integration with Angular looks very promising, after addressing the small interop glitches with type mapping it may be quite expressive and straightforward. I probably will shelve Knockout for now and explore Angular.

Marrying ClojureScript and JS Frameworks – Knockout Edition

A while ago I began to play with ClojureScript and tried to get it to work with popular frameworks. I played with a few of them, most recently with Knockout.js. This post sums up those efforts and my not-so-optimistic view on ClojureScript.

  • I tried “bare” jQuery. It was pretty smooth.
  • I tried Backbone.js. I got it to work on a simple example, though one reader on Twitter rightfully commented that ClojureScript was hideous. Yes, that Backbone example is hideous. Later on I tried to do something less trivial. Eventually I fled in horror, thanks to impedance mismatch between heavily OO Backbone and non-OO ClojureScript sauced with my ignorance in CLJS (and Backbone).
  • I also gave Angular.js a shot. It started really smooth, because Angular proudly states that it doesn’t rely on object-oriented programming so much. It was great. Right to the moment when I started arguing with the compiler renaming my variables, soon followed by discovery that Angular and Closure are no go.

So, the time has come to another experiment – this time Knockout.js. I followed the official tutorial and here is what I eventually came up with.

The Page

The complete page in Hiccup looks like this. Nothing particularly exciting here.

(defn render-body []
      [:p "First name: " [:strong {:data-bind "text: firstName"} "todo"]]
      [:p "Last name: " [:strong {:data-bind "text: lastName"} "todo"]]
      [:p "Full name: " [:strong {:data-bind "text: fullName"} "todo"]]
      [:p "First name: " [:input {:data-bind "value: firstName"}]]
      [:p "Last name: " [:input {:data-bind "value: lastName"}]]
      [:button {:data-bind "click: capitalizeLastName"} "Go caps"]
      (hp/include-css "css/todo.css")


The most interesting part is the ClojureScript code. Here’s one way to do it:

(ns hello-clojurescript)

(defn app-view-model []
  (this-as this
           (set! (.-firstName this) (.observable js/ko "Bert"))
           (set! (.-lastName this) (.observable js/ko "Bertington"))
             (.-fullName this)
             (.computed js/ko 
               (fn []
                 (str (.firstName this) " " (.lastName this))) this))
             (.-capitalizeLastName this) 
             (fn []
               (.lastName this (-> this .lastName .toUpperCase)))))

(.applyBindings js/ko (app-view-model.))

Yes, I do need to explicitly return “nil” there. Otherwise it returns this.fullName = ..., and that breaks KO.

It works, but it’s hard to defend it in comparison to the JS equivalent:

function AppViewModel() {
    this.firstName = ko.observable("Bert");
    this.lastName = ko.observable("Bertington");
    this.fullName = ko.computed(function() {
        return this.firstName() + " " + this.lastName();    
    }, this);
    this.capitalizeLastName = function() {
        var currentVal = this.lastName();     

ko.applyBindings(new AppViewModel());

Complete code can be found at my GitHub repository.

Better Way – Macro

This code can be made a lot better with a custom macro, as the one presented at StackOverflow:

(defvar name_model
    first_name (observable "My")
    last_name (observable "Name")
    name (computed (fn [] (str (. this first_name) " " (. this last_name)))))

(. js/ko (applyBindings name_model));

Now, that would be something!

… except for that defining macros in ClojureScript is harder than in plain Clojure, to the point that I haven’t gotten it to work yet.

Conclusions on ClojureScript

I spent quite a few hours poking at ClojureScript, and I have mixed feelings.

  1. It’s pretty hard to get ClojureScript to work with existing JS frameworks, mostly because using objects in CLJS requires so much ceremony.
  2. Contrary to plain Clojure, “fun” and “productive” aren’t the words that come to mind when I think of my adventures in CLJS. “Frustrating” and “intimidating” are much more appropriate. I’m constantly arguing with the compiler and trying to beat it to do the right thing, not having fun solving problems.
  3. Some stuff can be covered with macros, but all in all it feels very… rigid and constraining. I feel like every once in a while I’m bound to hit another rough corner, spend too much time on it, write another macro, and so on. All that only to bridge the gaps and make ClojureScript look more like… JavaScript. In fact, that feels like writing my own layer of macros to compile JS-like-DSL to ClojureScript.
  4. Perhaps there is a better way and I’m just doing something wrong. Maybe you’re not supposed to use those frameworks at all, but roll your own or use those few written in ClojureScript?
  5. Perhaps all of this makes little sense on such a small scale, and you need something really big to appreciate ClojureScript. You just need to invest many hours in passing the learning curve and macroing your way out. Maybe then it becomes more productive, modular and whatnot. I don’t know, in fact I have too little experience in JavaScript itself to answer such questions. I’m not very optimistic about it, though.

I am a DZone Most Valuable Blogger and JavaCodeGeek!

I’m happy to announce that at about the same time I became a DZone Most Valuable Blogger and a JavaCodeGeeks author. Some of my posts have been appearing on various blogs, community sites and aggregators for a while (especially those on Clojure and functional programming), but being invited to participate in something like these two programs is quite a new experience.

Some parts of this blog is ranting and bragging, but the main purpose has always been to learn and share knowledge. I wouldn’t have learned so much without the blog – just getting something to work is a lot easier than understanding it enough to be able to explain it to someone. We all know that the community is quite demanding. I learned the hard way that writing too shallowly, repetitively, or without proper understanding is immediately punished. On the other hand, it’s truly exhilarating to see my post mentioned by people I really admire, or make it to the front page of Hacker News.

The most rewarding part is always the comments. Not only does it mean that someone has visited the site, but also that they actually cared to read the post and share their insights or related knowledge.

Thanks, guys!

Version-Based Optimistic Concurrency Control in JPA/Hibernate

This article is an introduction to version-based optimistic concurrency control in Hibernate and JPA. The concept is fairly old and much has been written on it, but anyway I have seen it reinvented, misunderstood and misused. I’m writing it just to spread knowledge and hopefully spark interest in the subject of concurrency control and locking.

Use Cases

Let’s say we have a system used by multiple users, where each entity can be modified by more than one user. We want to prevent situations where two persons load some information, make some decision based on what they see, and update the state at the same time. We don’t want to lose changes made by the user who first clicked “save” by overwriting them in the following transaction.

It can also happen in server environment – multiple transactions can modify a shared entity, and we want to prevent scenarios like this:

  1. Transaction 1 loads data
  2. Transaction 2 updates that data and commits
  3. Using state loaded in step 1 (which is no longer current), transaction 1 performs some calculations and update the state

In some ways it’s comparable to non-repeatable reads.

Solution: Versioning

Hibernate and JPA implement the concept of version-based concurrency control for this reason. Here’s how it works.

You can mark a simple property with @Version or <version> (numeric or timestamp). It’s going to be a special column in database. Our mapping can look like:

@Table(name = "orders")
public class Order {
	private long id;

	private int version;

	private String description;

	private String status;

	// ... mutators

When such an entity is persisted, the version property is set to a starting value.

Whenever it’s updated, Hibernate executes query like:

update orders
set description=?, status=?, version=? 
where id=? and version=?

Note that in the last line, the WHERE clause now includes version. This value is always set to the “old” value, so that it only will update a row if it has the expected version.

Let’s say two users load an order at version 1 and take a while looking at it in the GUI.

Anne decides to approve the order and executes such action. Status is updated in database, everything works as expected. Versions passed to update statement look like:

update orders
set description=?, status=?, version=2
where id=? and version=1

As you can see, while persisting that update the persistence layer increments the version counter to 2.

In her GUI, Betty still has the old version (number 1). When she decides to perform an update on the order, the statement looks like:

update orders
set description=?, status=?, version=2
where id=? and version=1

At this point, after Anne’s update, the row’s version in database is 2. So this second update affects 0 rows (nothing matches the WHERE clause). Hibernate detects that and an org.hibernate.StaleObjectStateException (wrapped in a javax.persistence.OptimisticLockException).

As a result, the second user cannot perform any updates unless he refreshes the view. For proper user experience we need some clean exception handling, but I’ll leave that out.


There is little to customize here. The @Version property can be a number or a timestamp. Number is artificial, but typically occupies fewer bytes in memory and database. Timestamp is larger, but it always is updated to “current timestamp”, so you can actually use it to determine when the entity was updated.


So why would we use it?

  • It provides a convenient and automated way to maintain consistency in scenarios like those described above. It means that each action can only be performed once, and it guarantees that the user or server process saw up-to-date state while making a business decision.
  • It takes very little work to set up.
  • Thanks to its optimistic nature, it’s fast. There is no locking anywhere, only one more field added to the same queries.
  • In a way it guarantees repeatable reads even with read committed transaction isolation level. It would end with an exception, but at least it’s not possible to create inconsistent state.
  • It works well with very long conversations, including those that span multiple transactions.
  • It’s perfectly consistent in all possible scenarios and race conditions on ACID databases. The updates must be sequential, an update involves a row lock and the “second” one will always affect 0 rows and fail.


To demonstrate this, I created a very simple web application. It wires together Spring and Hibernate (behind JPA API), but it would work in other settings as well: Pure Hibernate (no JPA), JPA with different implementation, non-webapp, non-Spring etc.

The application keeps one Order with schema similar to above and shows it in a web form where you can update description and status. To experiment with concurrency control, open the page in two tabs, do different modifications and save. Try the same thing without @Version.

It uses an embedded database, so it needs minimal setup (only a web container) and only takes a restart to start with a fresh database.

It’s pretty simplistic – accesses EntityManager in a @Transactional @Controller and backs the form directly with JPA-mapped entity. May not be the best way to do things for less trivial projects, but at least it gathers all code in one place and is very easy to grasp.

Full source code as Eclipse project can be found at my GitHub repository.