Archive for the 'Programming' Category

Deleting child entity from many-to-many in grails

Today, i spend entirely too long trying to delete a entity in grails. Turns out it’s terribly simple (of course), but i just got stuck, so now (maybe) i can help others get unstuck. Let’s say you have the following:

class Parent {
  static hasMany = [children:Child]
}

class Child {
  static hasMany = [parents:Parent]
  static belongsTo = Parent
}

If you want to delete a child element (but not delete the parent), you can’t just call delete!. This gives you a constraint exception. This makes sense enough. First, you need to remove all the associations between the parent and the child. Okay, so my next try was this:

child.parents.each { child.removeFromParents(it) }
child.delete()

BAM!

java.util.ConcurrentModificationException

Okay, so that didn’t work. This confused the heck out of me for a while, but then i finally found something that make sense: i was removing elements from the set that i was iterating over. Remember, all these associations are managed by hibernate, and when you call removeFrom, you are changing the collection. Here was my solution:

def tmp=[]
child.parents.each { tmp << it }
tmp.each { child.removeFromParents(it) }
child.delete()

And that worked like a charm. Anyone know a cleaner way to do this, or is this a recommended mechanism? The grails docs weren't totally clear on this.

Short examples of jQTouch and chain.js

Recently, I got back on track with the RIA meetup and put together a brief overview of two jQuery libraries that I have found useful recently: jQTouch and chain.js.  I’d like to briefly recap that session here and post the code that I wrote to demonstrate how they work.  I’d like to thank and acknowledge David Kaneda and Rizqi Ahmad, the authors of these two libraries, for sharing their insightful work with the world.

Let’s begin with a quick overview:

jQTouch

  • What: A jQuery library (more like a framework actually) that provides tools that will make an HTML/JS/CSS app look and feel more like a native iphone application
  • Key Advantages
    • Provides a set of stylesheets that make extensive use of the safari-specific classes.  These enable CSS based transitions, gradients, and much more.
    • Implements a “page management” framework that allows you to construct a “multi-page” experience within a single HTML file

Chain.js

  • What: jQuery library that binds a javascript array to an HTML template.  It exists within the realm of JS template engines; however, it’s texture is a little more data-driven
  • Key Advantages
    • Abstracts the relationship between your Model and View, allowing for a cleaner client-side architecture
    • Override-able sorting and filtering of views.

And now, let’s turn our attention to three very simple example files that I’ve included that demonstrate how to use these libraries.  Please download the ZIP file here and extract it to a directory of your choice.  Then just open the HTML examples files in a browser.  They should work fine as all paths are relative.

Example 1 – Hello, jQTouch World

This file is simply a shell for holding a jQTouch application.  Its only functionality is an ability to click on the “Go Forward” link that moves the application to a second screen.  From there you can click to go back to the main homepage.

Use this example to understand how the jQTouch framework selectively displays DIV tags that sit as direct children to the main BODY tag.  The DIV with ID ‘home’ is displayed by default.  You are able to navigate to other DIVs (which are hidden by default) by clicking on an anchor tag that uses the # syntax to identify the ID of the DIV.  Notice the use of a few special classes that cause toolbars to show and buttons to render.

The documentation on these special classes is a bit thin.  I’ve resorted to simply combing the CSS files to figure out which classes are available.

Example 2 – Using Chain.js to build a dynamic list

In this example, I demonstrate how one can use Chain.js to build a simple dynamic list.  The input box on the top is used as a filter.  Typing letters in there will constrict the list to show only those names that match.

Notice how Chain.js treats the unordered list with ID friends, as a template.  Once I’ve bound “friends” to the JSON array in the file (done by calling .chain()) Chain.js examines the contents of “friends” and replicates those elements for each element in the JSON array.  Also, chain uses the class attribute of elements and interprets it as a key by which it indexes into properties of the objects in the JSON array (phew.  Sorry for the dense language).  The result is that you have a complete unordered list that is bound to client side data.

Now that your data is on the client, chain gives you some neat tools that allow you to sort and filter the list.  Try them out by uncommenting the JS lines toward the top of the file.  It should be noted that if you are dealing with lists that are several hundred elements, you must be mindful of performance – especially if you are using this library on mobile devices that have limited processing power — lest you learn the hard way (like me ?)

Example 3 – Putting it together

Now that you are an expert at examples 1 and 2, example 3 will be easy.  It just combines the two previous concepts and shows how one might use these libraries to build a rich mobile web app.  The examples demonstrates a very simple master-details type of setup.  Clearly, in the real world, having all the data on the client like this probably wouldn’t fly, but now that you understand the mechanics, you can insert your own code to call back to your server.

Using this example as a starting point, try adding back the filter box, or perhaps set up a simple grid and use chain to sort the elements in the grid.

Conclusion

jQTouch and Chain.js are wonderful little libraries that accelerate your development of RIAs.  Although neither is perfect, I heartily recommend them if you are considering constructing a RIA experience for the mobile web.

Comparing Cairngorm and Model View ViewModel

Several months ago at our RIA meetup, I presented a short comparison of two client-side flex architectures: Cairngorm and Model View ViewModel. I’ve used both of these architectures in large-scale production projects, but for the purpose of simple comparison, I decided to demonstrate the two designs by implementing an identical application twice – once in each architecture.

If you aren’t familiar with the basics of these two RIA architecture patterns you can learn more here:

This post will not cover the basics of these two patters, quick google searches will reveal lots of that type of information. Rather, below, you’ll find links to the code for the two – functionally equivalent – RSS reader applications followed by a quick highlight comparison of how these two patterns compare.

To get started, grab the two projects: Cairngorm and MVVM. As you look through the code, note a few things:

  • I know it’s not perfect. This was done pretty quickly, and the group had the benefit of me explaining my intent as i went along
  • I know it’s too simple. This RSS reader example is really too simplistic to be considered a true demonstration of these two architectures. The application is really just a starting point for comparison rather than an exhaustive stress test. My comparisons and analysis is drawn more from previous experience than it is from the code that i post here.

That being said here are the major points for comparison:

  • Decoupling vs Clarity.  In general, Cairngorm – with it’s highly event-based architecture – decouples your view and your logic code more than MVVM does.  But that comes at a cost.  In Cairngorm, I often find it more difficult to trace the origin – and destination – of events.  Additionally, vanilla Cairngorm asks you to create a class for every single event in your system.  If you have a large system, that’s A LOT of events.  They eventually get confusing.  MVVM has less of this, but with the trade off that you need to be careful about putting too much logic or “smarts” in your ViewModel classes.  You need to find ways to decouple this logic without breaking the pattern
  • View Helpers vs ViewModels. When it comes down to it, despite what the flex docs (and my examples) seem to imply, more often than not, you’ll need to write code that interprets responses from the server before display.  In MVVM, the path to do this is relatively certain.  When a model is updated, your ViewModel hears the change, interprets the response, and passes the message on to the view.  With Cairngorm, if your goal is to keep logic outside of the MXML, you’ll likely need to write separate response classes that massage model data first and then place the data into the view.
  • Emphasis on Binding. While data binding can – and should – be used in both frameworks, MVVM really emphasizes data binding for just about everything.  In a well-factored MVVM view, everything, down to button state is bound to the ViewModel.  While this can be tedious at times, if you design your ViewModel classes well, this gives you a tremendous ability to do very comprehensive unit testing and have high confidence in the quality of your application.

I hope this was a helpful introductory overview of these two architectures.  Bottom line: they are both good but be sure to use your judgment when applying them.  Taken to an extreme, each has weaknesses.

Learning about Silverlight

On Thursday, the Carrboro RIA Meetup had it’s latest installment of RIA learning.  Rob Zelt, (and here) an expert on Silverlight and MS web technologies shared the basiscs of Silverlight with our group.  Thanks very much to Rob for sharing with the group!  It was a great session where I think everyone learned a lot.

Here are some of my key takeaways from the session:

  • Silverlight has a stunningly powerful ability to skin and layout components without touching a single line of logic code.
  • The “old” arguments that flash has such a wide install base it will be hard for MS to catch up are starting to be less relevant.  The Silverlight install base is growing and growing fast.
  • Silverlight 3 has awesome 3d rendering capabilities and will be able to deliver HD content efficiently
  • Coding patterns between Silverlight and Flex are quite similar (although Cairngorm is a little different on the flex side)
  • MS is working on RIA services, which seems strikingly similar to LCDS.  This is a great move as LCDS can be a great productivity boost to Flex teams

There was much more in the presentation, but these are the highlights that come to mind.  There was a suggestion at the end that we have a session where we compare building an app in Flex and Silverlight.  A great idea, and something we will definitely have to try.  If we do that, I’ll definitely post code examples here.

Thanks again to Rob!

Adobe AIR: Introduction and Overview

As I was preparing for tomorrows RIA Meetup, it dawned on me that it probably would be a good idea to use my blog as a way to both document and share the work that goes into the meetups. From now on (time permitting), every time we have a meetup, I’ll try to accompany it with a blog post.  Now on to the content:

Adobe AIR is runtime environment that liberates RIAs from the browser and brings them right onto a users desktop.  When I first heard of a AIR prior to it’s formal release, I (mistakenly) thought of it as an extension to the Flex SDK.  While this is correct in a limited sense, defining AIR in this way is too narrow.

In truth, AIR is desktop runtime that enables developers to build rich, web-enabled applications that are installed on a users OS.  Developers can build AIR apps with their choice of Flex, Flash, and even DHTML.  In the rest of this post I’ll build a case for why one would choose AIR and how AIR development differs across technology choices.

Why Choose AIR?

As you do when designing any software product, technology choices should be driven by customer requirements.  Here are some of the customer requirements that would start to point me toward AIR

  • Daily use.  A customer will use your app frequently and is willing to install the application (an extra step compared to viewing a web page) because it is accessed often
  • Connected.  The application relies on data out in the cloud.  It’s probably multi-user or social in some way
  • Need for offline use.  If offline use is a requirement, this could be a big push to AIR (or google gears, or some other local storage technology)
  • File system access.  Will the ability to read / write files on the users local machine enhance the usability or experience of the product?

Now let’s move one click down to some of the technical advandages you gain when choosing AIR

  • Your product loads faster.  No SWF DL or HTML page load.  Your code is local and will boot up faster
  • Multiple ways to store data including
    • File system access.  can read / write files
    • SQLite database
    • normal “browser-like” approaches like cookies
  • Desktop notifications.  notify users when there is some sort of state change
  • Control over the window.  Removing the standard looking window chrome does a lot more than you think to enhance the look and feel of your app.  the window can even be transparent… ooooh :)

Using AIR with Different Technologies

Another very cool thing about AIR is that there are multiple ways to make use of the run-time depending on your background.

If you are a Flash developer, you can use your familiar Flash CS4 product to create AIR apps.  I know the least about this option, so I’ll move on…

If you are a Flex developer (like me!) you can build an AIR app in much the same way that you would build a normal Flex app.  You have an extended API at your disposal and the configuation of the app is slightly different.  This page does a nice job of explicitly listing out all the API differences between Flex development and AIR development.  I personally will gravitate toward this option since I think Flex provides a nicer development environment and UI capabilities than DHTML when we are talking about desktop experiences.  The other cool thing is that as long as you are careful, it should be easily possible to port an app between a pure Flex browser experience and an AIR desktop experience.

Last but surely not least is DHTML.  So for all you web standards lovers out there (and i consider myself among those ranks), you can translate all your HTML / JS / CSS skills straight to the desktop and create disconnected and/or file system aware experiences.  Pretty cool stuff!  DHTML development comes with a few caveats (not the least among them is that use of eval() is limited due to security concerns.  It is overcomable, but needs to be pretty intentionally designed).  I haven’t looked, but i suspect that there are probably some pretty good JS libraries out there to make DHTML + AIR development a snap.

Getting Started and References

So there is my 2c introduction to AIR and why i think it is a truly compelling platfrom.  It is, of course, not the the answer to every problem in the world; however, for a certain subset of applications, AIR is a wonderful addition to a developer’s toolkit.

To get started with AIR, head to this adobe page and follow the directions.  In the Meetup, I plan on exploring the the APIs around windowing (including notification mechanisms in the system tray or application bar) and file read/write capability.  Obviously there is much more available, but i have a feeling we’ll be pressed for time with just that.

While preparing, i used the following very helpful references

thanks and have fun with AIR!

Javascript and Design Patterns

I recently read book on Javascript Design Patters that really helped me to write better, cleaner javascript code.  You can find it here.  Being completely new to JS, I was using the language in a really primitive way.  I was basically just responding to DOM events by calling functions directly.  If I needed to swap an image on hover, I called a method.  If I needed to validate a form, I called a method.  JS was just a tool to manipulate the DOM rather than an environment to build an application.

Of course, I knew this wasn’t the best way any self-respecting programmer would code, but i needed some inspiration since JS lacks all the normal constructs I am used from C++, Java, Flex or any other language that I consider myself proficient in.  After the Pro Javascript book, I had the tools i needed to start building applications and not what is essentially a javascript puppet show.

The first thing to go is the direct function calls.  If you think about it, calling a function directly from UI code like that is really a ‘no no’.  Really, what you want to do is fire an event which can be handled by any one or multiple event handlers.  This allows for better reuse and more complex interactions.  My approach was a simple command processor.  When some action happens, i fire an event.  The event enters into a loop where it is handled by Command that have registered as handling this event.  The commands can either be synchronous or async, it doesn’t matter.

All of this is simply done with about 50 lines of code, but without classes, singletons, and encapsulation is really difficult (for me at least) to dream up how to do it effectively.  Now, i’m happily MVC’ing away on the client side!

Splitting a Team By Architecture: Bad Idea

Lets say you are working on a project where there are multiple teams all working toward a common outcome.  You are the manager and you sit down with your architect / lead developer (which could be yourself for all that matters).  You know the solution you need to deliver for your customers and you have started to sketch out a diagram of what your software system will look like.  Perhaps it looks something like the random image i grabbed on the left.

You scratch your head and say, “well, lets have team A work on the front end and team b work on the back end.  Well have joe manage team A and jane manage team B.”

Bzzzt!  While this is of course the most straightforward, neat, and logic way break up your development team.  Is is really the best?  My opinion, as you might have guessed, is no.  Here’s why:

One of the basic arguments for splitting a team up into front end and back is that developers on each team have less to learn.  They can focus on a smaller domain and theoretically become more skilled in that limited domain.  This makes good sense IF the main reason why a project fails is because developers didn’t understand their technical domain deeply enough.  Is that really the reason?  I think not.

I think one of the biggest reasons why projects fail is a lack of

  1. Deep understanding and focus on a customer problem (where a customer can be internal or external)
  2. Poor communication within a development team and around a development team.

So, if those two reasons resonate with you,  why would you split a team across front-end back and lines?  Splitting a team that way only serves to:

  1. Remove the back end team from direct exposure with the end customer
  2. Push communication channels up creating a bottleneck at the top

Lets go through my rational for why splitting a team causes these two problems and why they are so bad to begin with

Backend Team has less exposure to customer

All of a sudden, the goals for your backend team just completely changed.  What once was a common goal of “lets deliver a great product to our customer” just became “lets build a reusable/scalable/flexible/<insert quality attribute here> backend for the front-end team”.  While architecture purists might disagree with me, i think this is a very dangerous thing.  I’m all for great architecture.  There are few things more satisfying that beautifully organized code; however, this does not always deliever in the ways that you want to.  Remember what you are being judged on: how much the end customer loves what you build.  nothing else.

Pushing communication channles up

When you have two independent teams that report to different managers you are effectively moving lines of communication up through managers and their managers.  At first, this doesn’t seem like such bad idea.  Take the burden of communication off individual developers.  Let them focus.  Let managers communicate.  This theory is great when the communication is external.  Managers should be shielding the team from external distractions.  However, this is absolutely dangerous when the communication you are blocking is internal team communication.  Internal team communication is never bad.  In complex software systems, the more team members know what their other team members are doing, the better.  This helps to reduce errors, cut down on mismatched expectations, and increase developer confidence.  I can guarentee that 80% of this good mojo will get lost when it’s translated through a manager.  She just became a bottleneck for good communication.

What do we do instead?

For all the reasons I list above, create very small teams that are oriented around end-to-end features of your software system.  it’s okay for individuals to specialize in particular technologies or pieces of architecture, but make sure that all members of your team are focused on a common customer and make sure that they are forced to communicate with one another.  Sure, this is definitely trickier from a managers perspective, but that’s okay.  If you have a good team with good managers, they’ll be able to handle it.  Sure, it’s not going to look as pretty when you put your progress in some nice bar graph in PPT ’07, but how important is that really anyway :)

Why anonymous functions are cool

A few months into learning about Actionscript, I started playing around with anonymous functions.  I found them to be a convenient way to do some basic event handling quickly and easily while reducing the complexity of the code.

For review, an anonymous function in Actionscript looks something like this:

foo.addEventListener(EVENT, function (event:Event):void { bar++ } );

When you use an anonymous function in this way you gain two major advantages that I can see

  1. You are handling your event in the context of the request.  The code for the handler is in the same place as the code for the request.  This helps you to understand how your request will be handled when debugging
  2. The context of your request is held in the closure for the anonymous function.  This is a big point.  A closure makes is so that the variables which are in scope for the enclosing context will be available to the anonymous method.  This means that when your anonymous function is called back you have access to the variables which probably caused the method to be called.  Very helpful since otherwise you might have to preserve that context on your own.  much better to have the language do it

As I became more familiar with anonymous methods I started to use them in different ways to help me write more compact code (although it doesn’t always help readability).  For example, I often will create factories that output functions (along with their respective closure) to help reduce the amount of code I write.  Again and example:

public class Function Factory
{
    public static functionGenerator(foo:String, bar:int):Function
    {
        return function(woot:String):String
        {
            return foo + bar + woot;
        }
    }
}

Okay, so clearly a trivial example. Why was this worth the effort?  It was worth the effort for two big reasons:

  1. Because this generated function is now wrapped in a closure with the values that were passed in by the caller, we’ve just created a function that – while it looks the same to a future caller – is imbued with metadata that we inserted at runtime.  This means that the caller of this method didn’t have to worry about holding onto that metadata
  2. While what we did is semantically equivalent to instantiating a class and returning a member function of that class, the effect is less code and fewer files to clutter up a clients understanding of the API.  For a client, as long as they understand how to call the method (one of the downsides.  i wish there was a good way to typedef a function in Actionscript) they don’t have to worry about anything else.

So, I hope that was a brief but useful look at why anonymous methods in Actionscript are cool and useful.  I will warn however, they can be dangerous if used too much.  The closure can consume memory, and if you are not careful when doing event handling you can end up with some nastly leaks on your hands.  So all in all, be careful, but go ahead and use anonymous methods.  They help you out a lot!

ps.  This is my first post with the Code Markup plugin.  So if this doesn’t work right away, i’m still learning :)

Flex. The Good and the Bad

Over the last two years, I’ve had the opportunity to build up relative expertise in Adobe’s Flex framework.  I’ve mostly been working on flex’s middle tier, tying the flex client to our JEE backend.  It’s been a pretty crazy journey and i’ve learned a lot along the way.  This post is a long overdue review of my impressions about the Good and the Bad with Flex.  I hope it is useful to someone making the choice to use this technology


The Good

  • Looks good with little effort.  Looks amazing with more effort.  Out of the box UI controls that look good and just work
  • Actionscript.  The flexibility of Javascript with a typesystem that works when you need it and gets out of your way when you don’t
  • Powerful, efficient remoting with BlazeDS



The Bad

  • Binding, especially initialization of it, generally only works well for the simplest cases.  As you create more abstraction and complexity in your models, I have generally found that binding becomes a royal pain
  • It is very easy to bloat your SWF with images, resources, and other misc things that create a subobtimal initial load time.  You can fix this problem, but, in the beginning it was too easy to do things the ‘wrong’ way
  • The designer in Flex Builder is bordering on completely useless.  I find that it really only works in the simplest cases.  As soon as you have a complex, dynamic UI, the designer is done.  Not that this is all bad of course.  I have a quite positive impression of Flex Builder as a whole.

Overall

On the whole, i must say that i have really enjoyed learning and working with flex.  The ultimate question of course is:  “Would i use it again?”  I’m not sure.  Like all things, it depends on the project.  My current project is attempting to do an entire application in one SWF.  I’m not sure i would do that again.  I would, however, like to take the approach of injecting some flex here and there in an otherwise ‘standard’ web app.  Using the JS bridge that comes with flex, I think you could build some very cool experiences that are both fast for the user but also rich in content.