Category Archives: Programming

“Growing Object-Oriented Software, Guided by Tests” (Book Review)

“Growing Object-Oriented Software, Guided by Tests” by Steve Freeman and Nat Pryce has been on my to-read list ever since I saw Steve at 33rd Degree 2011. Even though I did not really like the presentations, somehow I became intrigued enough.

The first two parts of the book explain what object-oriented programming and test-driven-development are. It explains the “tell, don’t ask”, encapsulation and information hiding, some pieces of design and architecture (ports and adapters). It contains a short explanation of what TDD is (the basic 3-phase cycle known to everyone) and extends it beyond unit tests, up to blackbox integration tests.

The third part is a long case study – writing a real, nontrivial application with Swing GUI, XMPP and interesting domain. The study is pretty long, and even though I’m not a fan of them this one is just perfect. It’s very easy to follow, taking small well-explained steps. It’s a rich and very practical example of TDD walking hands in hands with elegant object-oriented design.

The fourth part is a long and interesting catalog of “test smells” – shows the links between test complexity and readability and quality of covered production code; tells how to write elegant, useful tests and assertions; gives advice on how to write tests that won’t be too constraining in future; and more. The last part explores some practical sides of testing in multithreaded environment and around persistence.

I loved the book! It’s an awesome piece of work that covers so many topics in such a clear, deep and interesting way that I would call it a must read for everyone. It’s a great book on testing, but not just that. It shows where testing fits in the software development process and explains the very important link to object-oriented design. It’s full of small, hidden gems (not only about software testing itself) that I will remember for a long time. At the same time it’s also very practical, pragmatic and concise.

I think it has much to offer to people of any skill level (perhaps except for novice). Even though I have been doing OOP and TDD for years, I really enjoyed it and I believe I learned much new stuff.

If you haven’t done so yet, do yourself a favor and go read it now!

ClojureScript Painkiller (for OOP)

When I learned and used ClojureScript, I really hated writing code that looks like this:

(defn Bag []
  (this-as this
           (set! (.-store this) (array))
           this))

(set! (.. Bag -prototype -add)
      (fn [val]
        (this-as this
                 (.push (.-store this) val))))

(set! (.. Bag -prototype -print)
      (fn []
        (this-as this
                 (.log js/console (.-store this)))))

(def mybag (Bag.))
(.add mybag 5)
(.add mybag 7)
(.print mybag)

That’s so much ceremony and repeated waste!

I know it’s not how you’re supposed to write ClojureScript, but sometimes you have to (for example when working with OO libraries).

What do you do with such code? Cover it with macros!

So I wrote two little macros that you can just pick up and use right away in your ClojureScript, so that it can look like:

(defn Bag []
  (this-as this
           (set! (.-store this) (array))
           this))

(set-obj-fn Bag.prototype.add [val]
            (.push (.-store this) val))

(set-obj-fn Bag.prototype.print [val]
            (.log js/console (.-store this)))

Or just a this-as shortcut:

(set! (.. Bag -prototype -add)
      (obj-fn [val]
        (.push (.-store this) val)))

Source with complete sample is on github. The library is on Clojars, so to use it all you need is [cljs-painkiller "0.1.0"] in your project.cljs. Enjoy!

Get Started with ClojureScript with Leiningen Templates

When I was about to get started with ClojureScript, I was discouraged by the fact that I apparently had to figure out so much before getting a trivial project up and running.

Eventually I learned, built and showed a minimal application running with just Leiningen and Ring, and a little bit of jQuery in ClojureScript.

Some time later Kyle Cordes showed me cljs-template. It’s a Leiningen template created by Chris Granger, also known as the guy behind Noir and Light Table. That was quite fun. All you need to get a project up and running is:

lein new cljs-template my-project
cd my-project
lein run

That’s it, you’re now running a Noir application with ClojureScript in client (jQuery included). You can start hacking at the CLJS source and see changes in browser immediately.

I soon discovered that it was a few months old, using Clojure 1.3, dated build of ClojureScript and pretty much everything. Eventually (thanks to Kyle and Raynes) I got push access to the project and updated everything, so it should be in even better shape now.

I am not sure where cljs-template is going though, with Noir itself going away. I also found one bit missing: That template is awesome to get up and running and show off a demo, but you would still need to do some manual plumbing to make such a project work for a real application (with leiningen hooks on compilation etc.).

That’s why I created another template: cljs-kickoff. Like my first steps, it’s really minimal: just Ring, lein-cljsbuild and ClojureScript. Fewer files, fewer dependencies, very easy to grasp.

To kick it off, just run:

lein new cljs-kickoff my-project
cd my-project
lein run

It will compile the ClojureScript file included in the project and start Ring server with it.

In another shell, you can run:

lein cljsbuild auto

This will start lein-cljsbuild in the auto-compile mode. Whenever the CLJS source changes, it will be automatically recompiled and the running application will pick it up after reload.

Compared to cljs-template, this template is much smaller and only uses very basic, popular and mature pieces (just Ring and CLJS). It also has all the “real” Leiningen hooks in place: CLJS compilation is included in lein run, lein jar and lein uberjar.

I hope it all makes someone’s life easier by making the first step on CLJS path as easy as possible. Happy hacking!

“ClojureScript Up and Running” (Book Review)

I’ve recently finished the “ClojureScript Up and Running” book by Stuart Sierra and Luke VanderHart. Here’s a quick review of it.

It opens with a quick introduction which attempts to present ClojureScript as the alternative to (or a matured “version” of) JavaScript. Then it immediately dives into gory technical details:

  • It shows how to set up a Leiningen project with lein-cljsbuild and explains the compilation process in detail (with all the possible parameters and modes).
  • It explains the development process – getting ClojureScript, working with browser REPL, testing, packaging for use with CLJS and plain JS applications.
  • It gives a basic introduction to the language, which really is a head-first guide to Clojure (though I suspect it’s far from enough for people who don’t know Clojure, and for those who do know it it’s no use).
  • It explains integration with JavaScript, but mostly on the level of Google Closure – exporting functions and namespaces for the world outside, or using external libraries with Closure advanced compilation.
  • It explains integration with Clojure, especially using EDN as an alternative to JSON.
  • It also introduces a few CLJS libraries (little code, just an idea of what a library does). Among others it includes C2, jayq, enfocus, core.logic, domina. Google Closure is on the list as well.
  •  

    There are many things I missed, though.

    First and foremost, it does not do enough to explain why we need ClojureScript. It does not really try to convince anyone, it’s pretty much a very technical “up and running” guide.

    It does not tell you how to write ClojureScript code. The explanation of setup, compilation and integration is great, but that’s all there is. Actually, there’s little about ClojureScript itself in the book. It’s like (unconvincingly) telling you that Java is the more robust and productive alternative to C++, showing how to use javac and Eclipse, “Hello World”, and a brief indication that there’s also JEE and Swing and this and that. I wish it had some case studies, chunks of actual ClojureScript code, some discussion of architecture, patterns, sample applications…

    One more thing I did not like is that it apparently ignores the JavaScript world (except for Google Closure). There are many rich and mature JavaScript libraries out there that solve many problems, and this book has not a word on the common ways to integrate them. I spent a good while experimenting with CLJS with Backbone, Knockout, Angular and jQuery, and it’s quite a difficult, frustrating task. I know I can write a CLJS library to do the same things that Knockout does, but I would prefer to learn how to integrate the existing library with my CLJS application to solve a real problem, or be introduced to a pure CLJS alternative that someone has already created.

    Perhaps it reflects the current state of ClojureScript – not yet very mature or stable, without mature and established libraries, patterns.

    All in all, I have mixed feelings. The book is very dense and concrete, and delivers much content on so few pages. It’s true to its title – gets you up and running, and does it very well. But then immediately leaves you alone in the woods. We are yet to see “The ClojureScript Book”.

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.

Scope

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.

Code

Flatiron Director

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Flatiron Director Sample</title>
    <script src="https://raw.github.com/flatiron/director/master/build/director-1.1.6.min.js"></script>
    <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 });
    router.init();
    </script>
  </head>
  <body>
    <ul>
      <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>
    </ul>
  </body>
</html>

Sammy.js

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Sammy Sample</title>
    <script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
    <script src="https://raw.github.com/quirkey/sammy/master/lib/min/sammy-latest.min.js"></script>
    <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() {
          viewBook(this.params['id']);
          console.log("An inline route handler.");
        });
        this.get('#:route', wildcard);
        this.bind('run-route', listener);
      }).run('#');
    });
    </script>
  </head>
  <body id="main">
    <ul>
      <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>
    </ul>
  </body>
</html>

Notes

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.

Verdict

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
  (array
    "$scope"
    CTodoCtrl))

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.

ClojureScript!

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;

with:

(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);
});

with:

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

Verdict

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 []
  (hp/html5
     [:head]
     [: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-js 
        "//ajax.aspnetcdn.com/ajax/knockout/knockout-2.1.0.js"
        "js/cljs.js")
      (hp/include-css "css/todo.css")
      ]))

ClojureScript

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"))
           (set! 
             (.-fullName this)
             (.computed js/ko 
               (fn []
                 (str (.firstName this) " " (.lastName this))) this))
           (set!
             (.-capitalizeLastName this) 
             (fn []
               (.lastName this (-> this .lastName .toUpperCase)))))
  nil
  )

(.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();     
        this.lastName(currentVal.toUpperCase());
    };
    
}

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:

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

	@Version
	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.

Configuration

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.

Why?

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.

Demo

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.

JDD 2012

Last week I attended the JDD 2012 conference. Here’s a bunch of very quick notes from the talks.

  • Rebecca Wirfs Brock, Joseph Yoder “Pragmatic, Not Dogmatic TDD: Rethinking How We Test” – nice presentation about TDD, felt a bit like theater (dialogue between two presenters). A few good points to show that TDD is not only about the fast red-green cycle (anyone thinks so, by the way?). Little gem: Use pomodoro specifically to break the flow, take a step back and look at the big picture.
  • Jarosław Pałka “The deconstruction of architecture in times of crisis” – very good talk about applying system thinking to software development. The theory is fairly well applicable to our craft, and the interdisciplinary view helps you see it in different perspective. Briefly explained some pieces of the theory as well as a few concrete examples (tragedy of the commons, boiling frog syndrome). I only found one important bit missing: Theory of constraints. Suggested reading: Thinking in Systems: A Primer.
  • Jakub Kubryński “Microbenchmarks performance in the smaller scale” – difficult choice (in conflict with Jessica Kerr’s FP/OOP talk), but I went for this one since the topic was less familiar. And I don’t regret it. I learned a ton about Java execution model: The role and place of JIT, possible optimizations, and finally the impact on microbenchmarks (and ways to do them better).
  • Sławomir Sobótka “Evolutionary Distillation of Architecture” (in Polish, I took the liberty of translating the title) – introduction to ports & adapters (aka hexagonal architecture). As usually, served in a broader context on thinking about how we code, what tools we use and why we should constantly learn new ones. As always, very entertaining, professional and inspiring. Little gem: If someone only knows entity and service, he’ll go at great lengths implementing everything with just those two concepts. Related reading: Hexagonal Architecture by Alistair Cockburn.
  • Piotr Bucki on cross site scripting attacks – nice presentation on XSS, discussing various ways to protect an application: input sanitization and validation, escaping on input and output, white list filtering for places which need to allow special content (like auction descriptions with limited HTML). Conclusion: Sanitize and validate input, escape everything on output. Careful, include all directions and outputs – validate batch import from files, don’t even trust your own logs (someone could deliberately execute an invalid request to have it logged, and then XSS into your admin log viewer). Solid, though not spectacular talk.
  • Wiktor Żołnowski “Reversed Tests Pyramid ? dealing with legacy code” – great idea on approach to testing legacy code that can’t easily be covered with unit tests. Start with end-to-end tests (in bigger number that would otherwise be necessary) to gain some understanding and confidence in refactoring. Write more and more lower level tests as you refactor. Eventually throw away slow higher level tests as they become redundant and invert the pyramid as it should be. Quite fun, felt almost like a BOF session (appropriate for the evening). Hated one bit: Looking down upon the audience and repeating “I moved from development to coaching a few years ago”, “This is probably not interesting to you, developers” etc.
  • Thomas Sundberg “How to fail a software project fast and efficiently?” – pretty bad presentation. Could’ve been fun and sarcastic, but was really shallow and dull. Very little content, no argumentation.
  • Adam Bien “Java EE Future Is Now, But It Is Not Evenly Distributed Yet” – positive suprise! Went there just because I know so little about recent JEE and wanted to see something new. Very professional and dense. On our eyes Adam built a JEE app from scratch that demonstrated dependency injection (including configuration/params), differences between EJB and non-EJB life cycles, JSF, asynchronous execution (comet), event propagation… Very good mix of humor and live coding. Repeat, that was one spectacular live coding. I expected some fanaticism, but got none of that sort – some respect to Spring and others, but actually focusing on showing how JEE became lean and cool, not bashing the competition.
  • Patrycja Wegrzynowicz “Security Vulnerabilities in OpenSource Java Libraries” – stats done bad. Most of the presentation was a view statistical views on data for number of vulnerabilities discovered in various libraries and app servers. Ignoring information on how quickly the holes are patched (or whether there are workarounds known to community), it literally contained information such as over X years 100 issues have been discovered in Tomcat, 20 in JBoss, so Tomcat is much more likely to be insecure. But app servers from IBM and Oracle are even worse, they’ve had more issues discovered over so many years.
  • Hardy Ferentschik “JPA into the Cloud Introducing OGM and OpenShift” – demonstrated an experimental Hibernate extension to persist JPA to NoSQL databases (and deploy that to cloud using OpenShift). Not yet production ready, has some rough edges and I’m not completely sure why you’d want to do that. Anyway – challenging, interesting, well prepared and presented.
  • Gustaf Nilsson Kotte “Surviving the Zombie Apocalypse of Connected Devices” – proposal to use HTML hypermedia as the data format for all kinds of environments. Create a basic HTML model that can be viewed by any browser (leverage the fact that browser can display HTML data in a nice way). That can be used directly as default for most non-critical screens. For more interesting (or critical) areas or environments, use HTML merely as data format and build an app on top of that. We have tools to parse and generate HTML, so why not use it as data format? Very interesting idea – instead of REST and all kinds of unprintable data formats, use a popular format that has decent support and can be displayed by any device. The talk was pretty hard to follow, though – too calm and sleepy.
  • Jessica Kerr “Git Happens” – very good talk on Git to close the conference. No live demos, very good explanation of basic concepts. Not just the happy path, and not overly optimistic. Also, Jessica is an excellent speaker – passionate (sometimes to the point of running, screaming and damaging equipment), but also with a very good plan and attention to detail.

All in all, I’m quite satisfied with this conference. Like any, it had some low points and on one or two occasions I skipped the talks because there was nothing interesting to me in that hour. Feels small and local compared to 33rd Degree, and doesn’t have the community vibe of Confitura, but certainly has its place. Anyway, I learned a few new things, most of the presentations were good and a few were great, so it definitely was worth it.