My Case for DTO’s

In many of my posts about Grails and Flex integration, I take for granted that I use Data Transfer Objects to transfer data between my Grails backend and my Flex frontend. Put simply, Data Transfer Object are pure data containing classes different from the domain entity classes used to store data in the backend. I take it for granted because I’m deeply convinced that it’s the best way to do things and so far, experience has never proved me wrong. But I often get this question in comments or by mail (this is for you Martijn): why bother create an entirely separate class structure and copy data from entities to DTO’s and back instead of just using entities?

I’ve expressed my arguments a couple of times across various posts but I thought it would be nice to sum things up in here for future reference.

Where does it come from?

When I first started to work on enterprise applications and ORM-based architectures, it was with a Model-Driven Architecture framework called AndroMDA. AndroMDA was absolutely key in helping me getting started with Spring and Hibernate and I was especially inspired by one paragraph in their “getting started” tutorial, which I quote here:

Data Propagation Between Layers

In addition to the concepts discussed previously, it is important to understand how data propagates between various layers of an application. Follow along the diagram above as we start from the bottom up.

As you know, relational databases store data as records in tables. The data access layer fetches these records from the database and transforms them into objects that represent entities in the business domain. Hence, these objects are called business entities.

Going one level up, the data access layer passes the entities to the business layer where business logic is performed.

The last thing to discuss is the propagation of data between the business layer and the presentation layer, for which there are two schools of thought. Some people recommend that the presentation layer should be given direct access to business entities. Others recommend just the opposite, i.e. business entities should be off limits to the presentation layer and that the business layer should package necessary information into so-called “value objects” and transfer these value objects to the presentation layer. Let’s look at the pros and cons of these two approaches.

The first approach (entities only, no value objects) is simpler to implement. You do not have to create value objects or write any code to transfer information between entities and value objects. In fact, this approach will probably work well for simple, small applications where the the presentation layer and the service layer run on the same machine. However, this approach does not scale well for larger and more complex applications. Here’s why:

  • Business logic is no longer contained in the business layer. It is tempting to freely manipulate entities in the presentation layer and thus spread the business logic in multiple places — definitely a maintenance nightmare. In case there are multiple front-ends to a service, business logic must be duplicated in all these front-ends. In addition, there is no protection against the presentation layer corrupting the entities – intentionally or unintentionally!
  • When the presentation layer is running on a different machine (as in the case of a rich client), it is very inefficient to serialize a whole network of entities and send it across the wire. Take the example of showing a list of orders to the user. In this scenario, you really don’t need to transfer the gory details of every order to the client application. All you need is perhaps the order number, order date and total amount for each order. If the user later wishes to see the details of a specific order, you can always serialize that entire order and send it across the wire.
  • Passing real entities to the client may pose a security risk. Do you want the client application to have access to the salary information inside the Employee object or your profit margins inside the Order object?

Value objects provide a solution for all these problems. Yes, they require you to write a little extra code; but in return, you get a bullet-proof business layer that communicates efficiently with the presentation layer. You can think of a value object as a controlled view into one or more entities relevant to your client application. Note that AndroMDA provides some basic support for translation between entities and value objects, as you will see in the tutorial.

Because of this paragraph, I started writing all my business services with only data transfer objects (what they call “value objects”) as input and output. And it worked great. Yes it did require a little bit of coding, especially as I had not discovered Groovy yet, but it was worth the time, for all the following reasons.

The conceptual argument: presentation/storage impedance mismatch

Object-relational mapping is what Joel Spolsky calls a “Leaky Abstraction“. It’s supposed to hide away the fact that your business entities are in fact stored in a relational database, but it forces you to do all sorts of choices because of that very fact. You have to save data in a certain order in order not to break certain integrity constraints, certain patterns are to be avoided for better query performance, and so on and so forth. So whether we like it or not, our domain model is filled with “relational choices”.

Now the way data is presented involves a whole different set of constraints. Data is very often presented in a master/detail format, which means you first display a list of items, with only a few fields for each item, and possible some of those fields are calculated based on data that is stored in the database. For example, you may store a country code in your database, but you will display the full country name in the list. And then when the user double-clicks an item, he can see all the fields for that item. This pattern is totally different from how you actually store the data.

So even though some of the fields in your DTO’s will be mere copies of their counterparts in the entity, that’s only true for simple String-typed fields. As soon as you start dealing with dates, formatted floats or enum codes, there is some transformation involved, and doing all that transformation on the client-side is not always the best option, especially when you have several user interfaces on top of your backend (a Flex app and an iPhone app for example), in which case you’re better off doing most of these transformations on the server.

In anyway, if you change the way you store data, it should not influence too much the way you present the same data, and vice-versa. This decoupling is very important for me.

The bandwidth argument: load just the data you need

In the master/data use case, when you display the list of items, you just need a subset of the fields from your entities, not all of them. And even though you’re using Hibernate on the backend with lazy-loading enabled, fields are still initialized and transferred over the wire. So if you use entity classes for data transfer, you will end up transferring a whole bunch of data that may never be used. Now it might not be very important for hundreds of records, but it starts being a problem with thousands of records, especially when there is some parsing involved. The less data you transfer the better.

The security argument: show only the data you want to show

Let’s say you’re displaying a list of users, and in the database, each user has a credit card number. Now of course when you display a list of users, you might not want everyone to see the list of credit card numbers. You might want to expose this data only in detail view for certain users with certain privileges. DTO’s allow you to tailor your API to expose just the data you need.

The error-prone argument: argh! Yet another LazyInitializationException!

Of course there are associations between your business entities, and by default, those associations are lazy-loaded, which means they are not initialized until you actually query them. So if you just load a bunch of instances from your entity manager and send them over to your client, the client might end up with null collections. Now of course you can always pay attention, or use some tricks to initialize associations up to a certain level before you send your data, but this process is not automatic and it’s very error-prone. As for using things like dpHibernate, I think it just adds too much complexity and uncontrolled server requests.

The laziness argument: Come on! It’s not that hard!

I think that most of the time, the real reason why people don’t want to use DTO’s is because they’re lazy. Creating new classes, maintaining code that does “almost” the same as existing code, adding some code to service implementation to copy data back and forth, all of that takes time and effort. But laziness has never been a good reason for ditching a design pattern altogether. Yes, sometimes, best practices force us to do more stuff for the sake of maintainability and robustness of our code, and for me the solution is certainly not to shortcut the whole practice, but just to find the best tools to minimize the added work. With its property support and collection closures, Groovy makes both creating, maintaining and feeding DTO’s as simple and fast as it can be. AndroMDA had converters. There are even some DTO-mapping frameworks like Dozer to help you. No excuse for laziness.

For me, all the reasons above largely overcome the added work to maintain a parallel DTO structure.

Now of course, this is a very opinionated topic and you will probably have a different view. So all your comments are welcome as long as they remain constructive and argumented.

Flex on Grails, Take 2: Part 3

At the end of the second article in this series, we ended up with a working application but it was not really ready for the real world because it had one major flaw: the URL of the AMF endpoint was hardcoded in the client in such a way that it was impossible to change after compilation and very hard to handle several environments (dev, test, prod). The solution to that problem is to integrate dependency injection into the mix.

Now there are a lot of such frameworks for Flex/ActionScript applications, including Parsley, Swiz, Cairngorm, etc. But I’ve never been a big fan of those big MVC frameworks that impose their own interpretation of the MVC pattern and completely limit the initial capabilities of Flex itself. For me, the Flex framework itself is clean enough that you don’t need all that overhead and it’s better to use a non-intrusive framework like Spring ActionScript. So that’s what we are going to do.

(more…)

Flex on Grails: Take 2, Part 2

This is a follow-up post to Flex on Grails, Take 2.

Task creation

Now that we have a basic working application, let’s improve it by adding some security in there. If your Grails application is still running, you can leave it that way as you won’t need to restart your backend every time you modify it. That’s the whole beauty and productivity of Grails and this plugin.

(more…)

Flex on Grails: Take 2

A little bit of history

When I first discovered Flex, one of my first obsessions was how to make it work with a Java backend. I’m a java developer at heart and my Java backend stack of choice back then was Spring/Hibernate-based. That’s why I published a series of full-stack articles that became quite popular. But another obsession of mine has always been productivity so when I discovered Grails, it became my new preferred environment and I started looking for ways to plug a Flex frontend into a Grails backend. All of this work culminated in the release of my Grails BlazeDS plugin which worked great but had a few limitations (only Java DTO’s, run-war instead of run-app, etc.). I mean, it worked great… until it didn’t. For some obscure reason, my plugin didn’t work at all with Grails 1.3.x. I fought with this for months, but there were just too many technologies involved (Groovy, Grails, BlazeDS, Spring-Flex, Spring, etc.) and my knowledge of some of those technologies was too shallow to really understand everything happening under the hood. That’s why I called upon SpringSource and/or Adobe to help me or provide the community with a decent Flex support for Grails. And guess what! They listened. A couple of months ago, I got in touch with Burt Beckwith, from SpringSource, who intended to work on that. So he asked me for feedback and really that’s all I did: I explained to him some of the issues I had with the plugin, the typical environment that we Flex developers work with, etc. And today… TADAAAA! The new Flex support plugins are here.

(more…)

Mac Runtimes, What a Mess!

First of all, let’s make things clear: I’ve been a very satisfied Mac user for the past 4 years or so, but I’m also a Java and a Flex developer, which means I have interests in all three of those technologies. And yes, I’m also a big fan of Steve Jobs, but despite all expectations, I try to be lucid about him and some of his weirdest choices/decisions/open letters ;o).

The problem I have at the moment is that, in the name of sensationalism, a lot of blogs post with titles like “Macs won’t have Flash anymore”, or “Java is dead on the Mac”, as if it was just an evil continuation of the “no Flash on iPhone/iPad” fuss that started at the beginning of this year. Now it’s certainly a great way to draw attention to those sites who only live thanks to advertisement, and hence number of visits. But let’s try to reestablish a few realities here.

First off, let’s talk about what everybody has at the back of their head when they think about Apple and runtimes: iOS. Yes, iOS doesn’t support any alternative runtime. In fact, besides Javascript, iOS doesn’t support any virtual machine. Flash and Java work on virtual machines and they’re not supported on iOS. There are 2 major reasons for that. The first one is performance, because a virtual machine, that is a software execution environment on top of a hardware one, will never be as performant as the native one. Despite all the optimization efforts that Adobe has done with Flash on mobiles, first experiences on Android tend to confirm that there’s still work to be done. Even though they have improved a lot in the past 3 years thanks to the iPhone impulse, mobile devices still run with very limited hardware capacities. And they still haven’t reached the point where they have a lot of free resources to spare, like personal computers have. So the official reason makes sense. But of course the less official reason is also important for Apple: iPhone’s number one sales argument is apps. When you think about it, it’s almost funny because when the first iPhone came out without an SDK, everybody complained about it, and then Steve Jobs answered that there was no use for a SDK. And obviously at that time, Apple was already working very hard on the App Store and the iPhone SDK. But when you know you have something huge in the pipeline, something that will make your device even more frightening to the competition, what is the best thing to say to the competition? “Don’t worry, this is just another one of our silly shiny gadgets that will just convince our existing fans”. And then a mere 18 months later, Apple comes out with not only an excellent SDK, but a whole new sales and distribution channel, and a marketing strategy that is based solely on all the apps your can install. I’m sure that there must have been a couple of WTF-moments at Nokia, RIM and others. So when your whole marketing strategy relies on your controlled and polished SDK and distribution channel, you have absolutely no interest in letting others in, be it J2ME crap (I’ve done J2ME development too, iark!) or the more threatening Adobe AIR. So let’s deal with it: no virtual machines on iOS, and whether we like it or not, it makes sense.

So are recent news just a continuation of that? Is Steve Jobs trying to eliminate all competition on the Mac too. NO! He’s not! It’s a completely different story!

Let’s start with Flash on the Macbook Air. Yes, the new Macbook Air doesn’t have Flash pre-installed. Actually, Safari does not have the Flash plugin preinstalled anymore. But nothing prevents you from installing it yourself. As nothing prevents you from installing Firefox and its Flash plugin as well. On iOS, it’s not pre-installed, and you can’t install it yourself. On MacOSX, from now on, it won’t be pre-installed but you will still be able to install it yourself. Huge difference! The Flash community has complained enough about the outdated version of the pre-installed Flash plugin. Of course Apple will not change their systems every time Adobe fixes a security or performance bug. So the best way to avoid any remanent hole, is to allow no hole at all by default. And if you need Flash, you just install the latest version and you’re good to go. That’s for the official reason. But as always there is… one more thing! One of the main marketing arguments for Flash is that, unlike any other cross-platform runtime, it’s installed on a crushing majority of machines, somewhere above 95% of them. But that is partly thanks to those integration deals that make Flash ship with every new PC or Mac, independently of the popularity of Flash as a development platform. Apple’s bet is that with the advent of HTML5, users will use the Flash plugin less and less often. But if they pre-install it, this drop in usage won’t reflect on Adobe’s marketing. Once again, whether we like it or not, it makes perfect sense for Apple. And it even makes sense to me: even if I’m a big Flash advocate, even if I think the HTML5 fuss is just oversold, I think Adobe has been a little too slow to react lately, as if they were resting on their dominance of the cross-platform runtime market. So everything that makes them fight harder to build a better development and runtime environment is good. And I’m sure they will fight. They just need to invest more in it. Mobile Flex development only in early 2012 (and that’s the first estimates, the ones that are always wrong) will just be too late for the show. So that’s it: no Flash plugin preinstalled in Macs means no Mac shipping with outdated security holes built-in and no built-in popularity bias either, which is good for competition. But nothing will prevent your from installing Flash yourself.

Let’s talk about Java now. When you read the news, you tend to feel like Apple’s war on competition is nothing personal against Adobe, that  it’s targeted at everyone else, that Java will be Steve’s next victim. But that’s just so untrue! First off, contrary to what happens with Flash, Apple never said that they would ship Macs without Java built-in. They just said that it would enter a pure maintenance phase and that they would stop supporting it… themselves! But once again, they won’t prevent anyone else to take over support for Java on the Mac. In fact, that’s probably why they took this decision: there was a time when Apple had their own interests in Java, when there was a Java-Cocoa bridge in the development environment, when Java was even a great way to make the Mac ecosystem richer, because a lot of developers would write their desktop applications in Java to support all platforms with a single code base. But of course, with the deprecation of Java-Cocoa bridge and the advent of the iPhone and what it means in terms of popularity for Objective-C and Cocoa native environment, Apple’s stake in Java has decreased dramatically. So much so that today, those who have the most interest in Java on the Mac are… those who support Java developers. And since Steve Jobs and Larry Ellison are known to be big friends, I’m sure Oracle and Apple are perfectly clear with who is going to take over. Maybe the community can help with Soy Latte and OpenJDK, but I can’t believe that Oracle won’t step up themselves, given the overwhelming Mac install base amongst java devs. And still, whatever the solution, Apple won’t prevent any one else to support Java and offer a Mac installation package for it.

So Flash and Java are not dead on the Mac! At least not based on existing statements and choices from Apple. But we can’t know what Steve has in mind, and I can’t help worrying about the end game of all this. Given the huge success of iOS, which makes perfect sense in the mobile world, I’m really afraid that Steve Jobs won’t know where to stop and will want to reproduce the same model on desktop. And I certainly don’t want that. I’m not ready for it yet. And I think a lot of people are not ready either, so if Apple moves too fast in this direction, they could loose a lot of customers in the process, especially if Steve Jobs starts this transition and then leaves this for others to deal with. But we’re not there yet. So please bloggers, keep your heads cold and please avoid feeding fear, uncertainty and doubt.

Adobe, SpringSource, Please Help us with Grails/Flex integration

I’ve been using Grails extensively for a year or so, and I love it, I really do. I even wrote a couple of plugins for it, including one for integrating Grails with Apple Push Notification Service. But since I’m always looking for productive ways to develop, I always thought that Grails and Flex were the best combination ever… until I hit the brick wall!

There’s a Grails Flex plugin, but it has 3 major issues:

  1. The Flex plugin has not been maintained for years, and it uses the old-fashioned way of integrating BlazeDS into Spring instead of the more modern, robust and easy to configure Spring BlazeDS integration library
  2. It doesn’t deal at all with authentication and authorization which is for me a critical issue in any remoting setup. And the Flex plugin doesn’t really offer a solution to that.
  3. The Flex plugin integrates BlazeDS3 and suggests you should mix your Flex sources with Grails project, which doesn’t make it easy to work on the Flex part using Flash Builder and its great data connectivity wizards.

Those are the 3 reasons why I’ve been working on the Grails BlazeDS plugin which works great with Grails up to version 1.2.x. Unfortunately I’m tackling some challenges with Grails 1.3. And even with Grails 1.2.x, there are still some limitations with Flash Builder, mainly due to the fact that

  • Flash Builder requires a standard WAR layout, which “grails run-app” doesn’t create
  • Flash Builder doesn’t like artifacts that Groovy adds to classes at compile time, so it’s not able to generate client-side stubs

So from a Grails/Flex integration standpoint, we end up being stuck between an old solution that is working but incomplete and not integrated in tools, and a more modern solution that does not work anymore and forces us to use some workarounds.

All the community needs to make this work is a little coordinated help from Adobe and SpringSource so that we can have:

  • a BlazeDS 4 + Spring BlazeDS 1.5 + Spring Security 3 integration plugin for Grails 1.3 and above
  • a data connectivity wizard that does not require a standard WAR layout and is capable of generating client stubs based on Groovy classes.

I’ve left a couple of messages on Grails mailing lists, Adobe forums and SpringSource forums, but so far, all my calls for help have remained unanswered. So if anyone is willing to help or support this ongoing initiative, it’ll be greatly appreciated. Just leave a comment if you need such a better Grails /Flex integration and maybe it will trigger a red light somewhere at Adobe and/or SpringSource. And if someone from Adobe or SpringSource is reading this, please help!

Grails/BlazeDS/Flex/iPhone Full Stack Part 2/3

In the previous episode, we built a simple Grails backend for the todolist application. In this installment, we will create a simple Flex 4 front-end for this backend.

The following assumes that you have already installed Flash Builder 4 (formerly known as Flex Builder), either in standalone mode or as an Eclipse plug-in.

(more…)

Grails/BlazeDS/Flex/iPhone Full Stack Part1/3

A couple of years ago, I published an article on this blog entitled “Flex, Spring and BlazeDS: the full stack!” and this article became very popular. Actually it broke my daily visits record. Today I’m gonna try to break this record again.

In the last couple of years, I’ve worked a lot with Flex and Spring. But in my eternal quest for productivity and user experience, I discovered Grails. Based on the same ideas as Ruby on Rails or Django, it combines a dynamic language – Groovy – with the power of “convention over configuration” to make it possible to create web applications in no time, thus allowing you to spend more time on your user experience.

Of course it’s not the only thing that has changed since then. Flex 4 is now finally out in the open. BlazeDS 4 too. And Flash Builder is finally productive enough for me to use it… in combination with IntelliJ IDEA of course.

All those evolutions in my toolset needed to be integrated, so I ended up building a Grails plugin to do just that: Grails BlazeDS plugin. And since this plugin could not be officially released without a proper demonstration, here we are.

I prepared this tutorial for a BeJUG talk I gave last week. So I want to thank Stephan Janssen and the BeJUG for inviting me… and for staying with me without throwing vegetables at me, given all the failures I had during the live coding session. For those of you who were there: I clearly identified PermGen space as the guilty part responsible for all these blank screens. In fact, since Grails migrated from Jetty to Tomcat as their runtime server, default java memory settings are not enough anymore, so I always configure my projects for that, but of course, in live, I forgot…

Anyway. I’m going to publish this tutorial in three episodes, each one of them being accompanied by its very own screencast on Vimeo (damn Youtube and their 10-minute limit!). But I’ll also publish the tutorial transcript right here for those who want to go faster.

Important note: this tutorial covers the following set of technologies in the specified versions:

In particular, it seems that Grails 1.3 that was just released a couple of days ago breaks Grails BlazeDS plugin. I’ll update both my plugin and this tutorial when I can make them all work together again.

(more…)

Presentations

Just a quick note about past and future talks. Yesterday evening, I gave a presentation at Brussels’ Café Numérique to set a few facts straight about Flash and try to stop th FUD madness. It was very funny trolling in live. Excellent atmosphere. If you’re a Belgian geek (or you don’t want to be afraid of technologies anymore) that’s the place to be every Wednesday.

I’ll also give a talk for BeJUG on May 6th about my new favourite stack: Grails, BlazeDS, Flex and iPhone. Be sure to join the BeJUG and book your seat at least one week before the event.

The Real Reasons Behind the Flash Debate

In my humble opinion, the main reason why the debate around Flash versus HTML5 (and Adobe versus Apple) has gone haywire during the past few weeks is that everyone is lying about their true motives (like in any apparently inextricable conflict):

  • Apple doesn’t want Flash on its closed devices like the iPhone, iPod Touch and iPhone because Flash would be an alternate content channel that would hinder Apple’s very lucrative iTunes business. And of course they won’t admit it because it would mean that they put business strategy before innovation.
  • Adobe has some technical issues with Flash because the codebase is very old and costs a lot to maintain. And they won’t admit it because it would make Flash look weak and unreliable on the long term.
  • Most HTML5 proponents started as amateur web developers, tinkering for years with poor technologies like HTML, CSS and Javascript, building entire businesses around their capacity to figure out all this mess out of trial and error.
  • Flash developers (including yours truly) have invested a lot of time, money and effort in tools, training and experience with the Flash platform, and are not so enthusiastic about throwing all of that down the garbage for yet another fashion tech. But of course we won’t admit that because we’re afraid to look like dinosaurs who refuse to evolve.

And since everybody uses pretexts, everyone will use every contradiction and approximation possible to maintain their cover. Like I said, wars work the same way: ideology hides facts. It motivates your troops to fight the other side until they’re dead, because the big guys, the ones who know about the real reasons simply can’t find a peaceful solution that would allow everyone to win.

It reminds me of a European civil servant who asked me this simple question once when I started a mission for the European Parliament: “Why do you think the European Union was created?” Naively I answered “so that one day we can be on equal foot with the United States.” “Wrong!” he said. “That’s not what Shuman and its friends had in mind. After World War II, they realized that the true source of the conflict between France and Germany, and by extension between their respective allies, was the repartition of natural resources in general, and most notably at this time, coal. But it’s hard to get people to fight for that kind of cause, so powers had to disguise it with ideology so that people would feel invested and do terrible things in the name of it. And they understood that if they didn’t cure the real sickness instead of fighting the symptoms like they had done after World War I, they could not prevent it from happening again. That’s the real reason why CECA was created, and then CEE, then EU. It was not a matter of power, it was a matter of peace.”

And that answer struck me because the same pattern repeats itself over and over again in a lot of contexts. Behind decades of war between Israel and Palestine, there’s a fight for water. Behind the war in Irak, there was a fight for gas. Behind the war for the future of web technologies, there’s a fight for customers. And the conflict is even more violent as it happens on 2 different levels: company-wise between Apple and Adobe, and community-wise between Flash developers and HTML developers.

The good news is that there’s a way for everyone to win peacefully once we reveal the real issues. There are enough customers for everyone. It’s not a zero-sum fight. The other side doesn’t have to lose so that we can win. The question is: will we be strong enough to reject the ideology and find a common ground at the community-level? Or will we let the big guys at Adobe and Apple hide behind ideology and use us as cannon fodder.