Allocating business logic in Grails

THE DILEMMA

I’ve been on a couple of larger Grails projects in the past year and half and I’m witnessing a disturbing phenomenon. The allocation of business logic responsibility across the abstractions that Grails provides today is causing considerable pain. Grails provides controllers, services and domain objects where business logic can reside. I’ll contend in this blog entry that these abstraction categories work well for small- to medium-sized Grails projects, but thing quickly start to unravel once your application gets to be large.

CONTROLLERS

I see a lot of business logic code in controllers these days. Controllers shouldn’t contain any business logic whatsoever. The controller’s responsibility is to handle the web request and response. Anything else should be delegated to a collaborator. Don’t do it!

DOMAIN OBJECTS

The next logical place to put business logic is in the domain class. Allocating responsibility here works to a point, but you will quickly encounter issues when you need business logic that resides in services. I’m not a fan of injecting Grails services into domain classes. This situation quickly spirals out of control and makes unit testing very difficult to perform. For simple per-domain business logic, free free to allocate to the domain class. Anything more, and it belongs in a service (or something else, which we’ll discuss in a bit).

SERVICES

So most business logic seems to end up in Grails services these days. That’s what the creators of Grails intended. I have no qualms about that. The beef I have with services is that a method is a crappy abstraction for representing business logic in the system. On larger Grails projects, the service approach seems to break down, as services seem to take on more and more responsibility, making them more difficult to test. I’m also witnessing a lot of code duplication; in it’s current incarnation, there is no delineation of public API services versus private services which the public API services compose larger sets of business logic with. What we end up with is large, hard-to-test service methods that collaborate with too many dependencies and do too much.

THE DESIRE

I want an abstraction in Grails that promotes proper factoring of business logic into unit-testable abstractions. These abstractions can be composed into larger abstractions to provide the necessary logic to fulfill the requirements of the system. The chain of responsibility design pattern may offer some value here. Individual commands that have a singular responsibility can be created, unit tested, and finally composed into “chains” of commands that provide the necessary functionality of the system. The command chains can be integration tested to ensure that the individual commands composition provides the functionality required by the customer/business. When new functionality is needed, a new command chain is created, reusing existing commands where appropriate and creating new commands where functionality does not exist. Spring Batch has a similar concept that is core to its design.

CONCLUSION

I hope to blog a bit more around this in the coming weeks. I really like Grails and would love to see its usage increase in the coming months and years. I think it has some really cool features that allow you to get up and running very quickly. The plugin system alone is a huge advantage to using Grails, because features like a Chain of Responsibility executor can easily be added to the core Grails system.

the best ways to store a tree structure in a relational DB

As always: there is no best solution. Each solution makes different things easier or harder. The right solution for you depends on which operation you will do most.

Naive Approach with parent-id:

Pros:

  • easy to implement
  • easy to move a big subtree to another parent
  • insert is cheap
  • Needed Fields directly accessible in SQL

Cons:

  • retrieving a whole tree is recursive and therefore expensive
  • finding all parents is expensive too ( SQL doesn’t know recursions… )

Modified Preorder Tree Traversal ( saving a start- & end-point) :

Pros:

  • Retrieving a whole tree is easy and cheap
  • Finding all parents is cheap
  • Needed Fields directly accessible in SQL
  • Bonus: you’re saving the order of childnodes within its parentnode too

Cons:

  • Inserting / Updating can be very expensive, as you’ll maybe have to update a lot of nodes

Saving a path in each Node:

Pros:

  • Finding all parents is cheap
  • Retrieving a whole tree is cheap
  • Inserting is cheap

Cons:

  • Moving a whole tree is expensive
  • Depending on the way you save the path, you won’t be able to work with it directly in SQL, so you’ll always need to fetch & parse it, if you want to change it.

I’d prefer one of the last two, depending on how often the data changes.

See also: http://media.pragprog.com/titles/bksqla/trees.pdf

Source

5 Awesome AngularJS Features

AngularJS is a great JavaScript framework that has some very compelling features for not only developers, but designers as well! In this tutorial, we will cover what I consider to be the most essential features, and how they can help make your next web application awesome.

AngularJS is a new, powerful, client-side technology that provides a way of accomplishing really powerful things in a way that embraces and extends HTML, CSS and JavaScript, while shoring up some of its glaring deficiencies. It is what HTML would have been, had it been built for dynamic content.

In this article, we will cover a few of the most important AngularJS concepts to get the “big picture.” It is my goal that, after seeing some of these features, you will be excited enough to go and build something fun with AngularJS.

Think of your model as the single-source-of-truth for your application. Your model is where you go to to read or update anything in your application.

Data-binding is probably the coolest and most useful feature in AngularJS. It will save you from writing a considerable amount of boilerplate code. A typical web application may contain up to 80% of its code base, dedicated to traversing, manipulating, and listening to the DOM. Data-binding makes this code disappear, so you can focus on your application.

Think of your model as the single-source-of-truth for your application. Your model is where you go to to read or update anything in your application. The data-binding directives provide a projection of your model to the application view. This projection is seamless, and occurs without any effort from you.

Traditionally, when the model changes, the developer is responsible for manually manipulating the DOM elements and attributes to reflect these changes. This is a two-way street. In one direction, the model changes drive change in DOM elements. In the other, DOM element changes necessitate changes in the model. This is further complicated by user interaction, since the developer is then responsible for interpreting the interactions, merging them into a model, and updating the view. This is a very manual and cumbersome process, which becomes difficult to control, as an application grows in size and complexity.

There must be a better way! AngularJS’ two-way data-binding handles the synchronization between the DOM and the model, and vice versa.

Here is a simple example, which demonstrates how to bind an input value to an<h1> element.

<!doctype html>
<html ng-app>
  <head>
    <script src="http://code.angularjs.org/angular-1.0.0rc10.min.js"></script>
  </head>
  <body>
    <div>
      <label>Name:</label>
      <input type="text" ng-model="yourName" placeholder="Enter a name here">
      <hr>
      <h1>Hello, {{yourName}}!</h1>
    </div>
  </body>
</html>

This is extremely simple to set up, and almost magical…

It’s important to realize that at no point does AngularJS manipulate the template as strings. It’s all the browser DOM.

In AngularJS, a template is just plain-old-HTML. The HTML vocabulary is extended, to contain instructions on how the model should be projected into the view.

The HTML templates are parsed by the browser into the DOM. The DOM then becomes the input to the AngularJS compiler. AngularJS traverses the DOM template for rendering instructions, which are called directives. Collectively, the directives are responsible for setting up the data-binding for your application view.

It is important to realize that at no point does AngularJS manipulate the template as strings. The input to AngularJS is browser DOM and not an HTML string. The data-bindings are DOM transformations, not string concatenations or innerHTMLchanges. Using the DOM as the input, rather than strings, is the biggest differentiation AngularJS has from its sibling frameworks. Using the DOM is what allows you to extend the directive vocabulary and build your own directives, or even abstract them into reusable components!

One of the greatest advantages to this approach is that it creates a tight workflow between designers and developers. Designers can mark up their HTML as they normally would, and then developers take the baton and hook in functionality, via bindings with very little effort.

Here is an example where I am using the ng-repeat directive to loop over theimages array and populate what is essentially an img template.

function AlbumCtrl($scope) {
    scope.images = [
        {"thumbnail":"img/image_01.png", "description":"Image 01 description"},
        {"thumbnail":"img/image_02.png", "description":"Image 02 description"},
        {"thumbnail":"img/image_03.png", "description":"Image 03 description"},
        {"thumbnail":"img/image_04.png", "description":"Image 04 description"},
        {"thumbnail":"img/image_05.png", "description":"Image 05 description"}
    ];
}
<div ng-controller="AlbumCtrl">
  <ul>
    <li ng-repeat="image in images">
      <img ng-src="{{image.thumbnail}}" alt="{{image.description}}">
    </li>
  </ul>
</div>

It is also worth mentioning, as a side note, that AngularJS does not force you to learn a new syntax or extract your templates from your application.

AngularJS incorporates the basic principles behind the original MVC software design pattern into how it builds client-side web applications.

The MVC or Model-View-Controller pattern means a lot of different things to different people. AngularJS does not implement MVC in the traditional sense, but rather something closer to MVVM (Model-View-ViewModel).

The model is simply the data in the application. The model is just plain old JavaScript objects. There is no need to inherit from framework classes, wrap it in proxy objects, or use special getter/setter methods to access it. The fact that we are dealing with vanilla JavaScript is a really nice feature, which cuts down on the application boilerplate.

viewmodel is an object that provides specific data and methods to maintain specific views.

The viewmodel is the $scope object that lives within the AngularJS application.$scope is just a simple JavaScript object with a small API designed to detect and broadcast changes to its state.

The controller is responsible for setting initial state and augmenting $scope with methods to control behavior. It is worth noting that the controller does not store state and does not interact with remote services.

The view is the HTML that exists after AngularJS has parsed and compiled the HTML to include rendered markup and bindings.

This division creates a solid foundation to architect your application. The $scope has a reference to the data, the controller defines behavior, and the view handles the layout and handing off interaction to the controller to respond accordingly.

AngularJS has a built-in dependency injection subsystem that helps the developer by making the application easier to develop, understand, and test.

Dependency Injection (DI) allows you to ask for your dependencies, rather than having to go look for them or make them yourself. Think of it as a way of saying “Hey I need X’, and the DI is responsible for creating and providing it for you.

To gain access to core AngularJS services, it is simply a matter of adding that service as a parameter; AngularJS will detect that you need that service and provide an instance for you.

function EditCtrl($scope, $location, $routeParams) {
     // Something clever here...
}

You are also able to define your own custom services and make those available for injection as well.

angular.
    module('MyServiceModule', []).
    factory('notify', ['$window', function (win) {
    return function (msg) {
        win.alert(msg);
    };
}]);

function myController(scope, notifyService) {
    scope.callNotify = function (msg) {
        notifyService(msg);
    };
}

myController.$inject = ['$scope', 'notify'];

Directives are my personal favorite feature of AngularJS. Have you ever wished that your browser would do new tricks for you? Well, now it can! This is one of my favorite parts of AngularJS. It is also probably the most challenging aspect of AngularJS.

Directives can be used to create custom HTML tags that serve as new, custom widgets. They can also be used to “decorate” elements with behavior and manipulate DOM attributes in interesting ways.

Here is a simple example of a directive that listens for an event and updates its$scope, accordingly.

myModule.directive('myComponent', function(mySharedService) {
    return {
        restrict: 'E',
        controller: function($scope, $attrs, mySharedService) {
            $scope.$on('handleBroadcast', function() {
                $scope.message = 'Directive: ' + mySharedService.message;
            });
        },
        replace: true,
        template: '<input>'
    };
});

Then, you can use this custom directive, like so.

<my-component ng-model="message"></my-component>

Creating your application as a composition of discrete components makes it incredibly easy to add, update or delete functionality as needed.

The AngularJS team feels very strongly that any code written in JavaScript needs to come with a strong set of tests. They have designed AngularJS with testability in mind, so that it makes testing your AngularJS applications as easy as possible. So there’s no excuse for not doing it.

Given the fact that JavaScript is dynamic and interpreted, rather than compiled, it is extremely important for developers to adopt a disciplined mindset for writing tests.

AngularJS is written entirely from the ground up to be testable. It even comes with an end-to-end and unit test runner setup. If you would like to see this in action, go check out the angular-seed project at https://github.com/angular/angular-seed.

Once you have the seed project, it’s a cinch to run the tests against it. Here is what the output looks like:

ddd

The API documentation is full of end-to-end tests that do an incredible job of illustrating how a certain part of the framework should work. After a while, I found myself going straight to the tests to see how something worked, and then maybe reading the rest of the documentation to figure something out.

We have covered six of the many AngularJS features that I love. I believe that these six features are essential for not only getting up and running with AngularJS, but also putting your application together in a way that is maintainable and extensible.

The website for AngularJS, http://angularjs.org, has plenty of working examples and plenty of excellent documentation. I also recommend checking out the amazing community on the AngularJS mailing list.

Source

15 JavaScript Template Engines for Front-end Development

1

JavaScript libraries in no way declining, and the number is growing each day. When it comes to building JavaScript applications, it’s better to rely on templates than on full-scale libraries, because it enables us to have a much cleaner code base, and much better workflow to work with.

I wrote recently that you should try and build your own JavaScript libraries, when it’s time. But, template engines take a little more knowledge and understanding of the language you’re working with, so it’s better to depend on something pre-built, like any of the libraries in this list.

2

You can find a list of these on Wikipedia, it’s a nice comparison of template engines for a lot of web’s programming languages, but that list isn’t really focused on one particular language, and so I wanted to see how many templates engines I could gather up for JavaScript.

If you’ve been developing with JavaScript, you’ll know a handful of these, but you might also learn about some new ones that had not crossed your path until now. I had a lot of fun putting this list together, so I hope you will enjoy it.

ICanHaz.js

3

Very simple to use library for doing templating with Mustache.js, another templating engine that we will be looking at shortly. With ICanHaz.js you define your Mustache.js template snippets in script blocks of type=”text/html” and give them an “id” as a title for your snippet (which validates, btw).

Hogan.js

4

 

Twitter loves to be a part of the open-source community. You can use Hogan.js as a part of your asset packager to compile templates ahead of time or include it in your browser to handle dynamic templates.

Again, includes the same style that Mustache.js does, only delivers everything in a much more quick and efficient manner.

Handlebars.js

5

Handlebars.js is an extension to the Mustache templating language created by Chris Wanstrath. Handlebars.js and Mustache are both logicless templating languages that keep the view and the code separated like we all know they should be.

mustache.js

6

It’s no doubt the most popular templating engine in the world right now, and almost every single library listed in this post is somehow related to, or inspired by Mustache. The documentation is very easy to read and understand, and highly recommended to use – works on pretty much every programming language that’s above average popularity level.

Transparency

7

Transparency is a client-side template engine which binds data to DOM. Write easily understandable, native HTML and everything is plain, good old JavaScript. No need to learn comprehensive templating syntax, it’s all transparent and easy to use.

doT.js

8

Just something for the Node.js community. doT.js is fast, small and has no dependencies. It was built in order to find the breaking point for speed and flexibility, and it certainly has achieved that feat.

Walrus

9

 

It aims to provide the essentials in such a compact manner that speed or templating doesn’t feel like an issue of its own, rather, Walrus is focused on making it easy for the developer to template his web apps.

Chibi.js

10

Chibi is all about saving bandwidth and time that it takes to present a template, it’s a little tiny JavaScript library that will help you better template your apps, and focus more on things like CSS, instead of using animations.

templayed.js

11

It’s the smallest templating engine you’ll come across, guaranteed. It’s also Mustache compilant and is very easy to use and understand, the official homepage features a great demo example that you can run and test code with, and on the GitHub page there are benchmarks and unit tests concluded, to show the efficiency of this library.

ECT

12

Just like templayed, ECT also has a demo setup on its homepage that you can play with and see live results. It’s built for speed, and claims to be the fastest templating engine for JavaScript. (built with CoffeeScript)

It’s compatible with Node.js, and has a very easy to understand syntax.

Pithy.js

13

An internal DSL for generating HTML in JavaScript. It’s great for small client-side projects, but not recommended to use for HTML heavy webpages.

T.js

14

T.js is a template engine that uses simple Javascript data structure to represent html/xml data.

Nunjucks

15

Built by Mozilla, Nunjucks is for those who need fast performance and flexibility that’s offered by the ability to extend the library with custom features and plugins.

Jade

16

Jade is designed primarily for server side templating in node.js, however it can be used in many other environments. It is only intended to produce XML like documents (HTML, RSS etc.) so don’t use it to create plain text/markdown/CSS/whatever documents.

Dust.js

17

Dust extends Mustache, and offers high quality performance compared to other solutions you might find in this list. Also includes a very easy to use, clean API.

JavaScript Template Engines

I didn’t try to provide samples, simply because a lot of these have live preview of samples available on their official documentation pages, and I don’t see the point in doing the same thing twice.

I hope that you were able to discover some new alternatives to use for your next project. I’m sure there are more of these out there, though these are the ones that made their presence felt the most.

Source

Other useful resources

http://jster.net/category/templating-engines

http://garann.github.io/template-chooser/

http://fiddle.rythmengine.com/

http://en.wikipedia.org/wiki/Comparison_of_web_template_engines

http://angular-ui.github.io/

http://html5boilerplate.com/

Building The User UI Using HTML5

We’ve just implemented the business services of our application, and exposed them through RESTful endpoints. Now we need to implement a flexible user interface that can be easily used with both desktop and mobile clients. After reading this tutorial, you will understand our front-end design and the choices that we made in its implementation. Topics covered include:

http://www.dreamstime.com/stock-photography-image35575712

  • Creating single-page applications using HTML5, JavaScript and JSON
  • Using JavaScript frameworks for invoking RESTful endpoints and manipulating page content
  • Feature and device detection
  • Implementing a version of the user interface that is optimized for mobile clients using JavaScript frameworks such as jQuery mobile

The tutorial will show you how to perform all these steps in JBoss Developer Studio, including screenshots that guide you through.

First, the basics

In this tutorial, we will build a single-page application. All the necessary code: HTML, CSS and JavaScript is retrieved within a single page load. Rather than refreshing the page every time the user changes a view, the content of the page will be redrawn by manipulating the DOM in JavaScript. The application uses REST calls to retrieve data from the server.

 ticket monster tutorial gfx single page app 58
Figure 1. Single page application

Client-side MVC Support

Because this is a moderately complex example, which involves multiple views and different types of data, we will use a client-side MVC framework to structure the application, which provides amongst others:

  • routing support within the single page application;
  • event-driven interaction between views and data;
  • simplified CRUD invocations on RESTful services.

In this application we use the client-side MVC framework “backbone.js”.

 ticket monster tutorial gfx backbone usage 58
Figure 2. Backbone architecture

Modularity

In order to provide good separation of concerns, we split the JavaScript code into modules. Ensuring that all the modules of the application are loaded properly at runtime becomes a complex task, as the application size increases. To conquer this complexity, we use the Asynchronous Module Definition mechanism as implemented by the “require.js” library.

Tip
Asynchronous Module Definition

The Asynchronous Module Definition (AMD) API specifies a mechanism for defining modules such that the module, and its dependencies, can be asynchronously loaded. This is particularly well suited for the browser where synchronous loading of modules incurs performance, usability, debugging, and cross-domain access problems.

Templating

Instead of manipulating the DOM directly, and mixing up HTML with the JavaScript code, we create HTML markup fragments separately as templates which are applied when the application views are rendered.

In this application we use the templating support provided by “underscore.js”.

Mobile and desktop versions

The page flow and structure, as well as feature set, are slightly different for mobile and desktop, and therefore we will build two variants of the single-page-application, one for desktop and one for mobile. As the application variants are very similar, we will cover the desktop version of the application first, and then we will explain what is different in the mobile version.

Setting up the structure

Before we start developing the user interface, we need to set up the general application structure and add the JavaScript libraries. First, we create the directory structure:

 ticket monster tutorial gfx ui file structure 67
Figure 3. File structure for our web application

We put stylesheets in resources/css folder, images in resources/img, and HTML view templates in resources/templatesresources/js contains the JavaScript code, split between resources/js/libs - which contains the libraries used by the application,resources/js/app - which contains the application code, andresources/js/configurations which contains module definitions for the different versions of the application – i.e. mobile and desktop. The resources/js/app folder will contain the application modules, in subsequent subdirectories, for models, collections, routers and views.

The first step in implementing our solution is adding the stylesheets and JavaScript libraries to the resources/css and resources/js/libs:

require.js
AMD support, along with the plugin:

  • text – for loading text files, in our case the HTML templates
jQuery
general purpose library for HTML traversal and manipulation

Underscore
JavaScript utility library (and a dependency of Backbone)

Backbone
Client-side MVC framework

Bootstrap
UI components and stylesheets for page structuring

Continue Reading