Your one stop for Groovy / Grails conferences and training

Training Schedule

Conference Schedule

Past Events

Resources

Tutorials and Articles

Event Management

Groovy / Grails Training and The 2G Experience are a production of the No Fluff Just Stuff Symposium Series. Since 2002, NFJS has produced over 130 technical events with over 21,000 participants. Be sure to attend The 2G Experience and find out what the NFJS experience is all about!

No Fluff Just Stuff

Speaker Blogs

Items:   1 to 50 of 2046   Next »

Json-lib: 2 years and counting
Posted By: Andres Almiray on Thu. Jul. 3, 2008

Yikes! been so busy at work that missed Json-lib's second anniversary by two days. Don't have exact download stats as sourceforge.net decided to give broken links for projects statistics for over a week now, last time I checked we were over the 78K mark ;-)

20 releases, 71 bug reports, 72 feature requests, 6 patches, 123 forum messages and countless direct emails we are still up and going strong. Thanks to everybody that has contributed to the project, and to the users too, we wouldn't be here if it wasn't because of you.

It’s ok to wet yourself every once in awhile
Posted By: Andrew Glover on Tue. Jul. 1, 2008

Dan North, the veritable progenitor of behavior driven development (or BDD), recently blogged about unnecessary DRYness (meaning don’t repeat yourself) with respect to clarity of intent when it comes to testing (in generic terms of the word). Essentially, in the case of a JUnit test, for example, by utilizing a setUp method and possibly other helper methods, the test itself becomes somewhat cluttered– one must jump around the code to truly understand the intention of the test in the first place. shh!

In fact, Dan says it quite nicely– tests (or stories, baby) are:

“examples [that] tell a story about what the code does… [and] clarity of intent is found in the quality of the narrative, not necessarily in minimising duplication.”

Thus, over utilizing the DRY principle can be ineffective when it comes to testing; indeed, he makes a great point! If tests or stories are intended to serve as “executable documention” doesn’t it make sense to make them as easy to read and understand as possible?

As such, because it’s my bag, I took the liberty of pondering the depth of favored term DRY and decided that when it comes to clearly expressing intent with respect to stories (as in the case of easyb) or tests, it often pays to be WET– that is, wholly express your tactics, baby.

You see, applying WET to, say, an easyb story then yields perhaps more text, but it leaves no room for misinterpretation, man. For example, imagine a story regarding discounts (this is my touchstone example that is in danger of itself becoming dry– no pun intended either, man). The high level story is such that VIP customers receive varying discounts depending on the amount of money a particular order has– you could even require a minimum number of items too (if you were attempting to move inventory). Thus, one scenario could be:

scenario "VIP customer with 3 items, over $30 receiving 10% discount", {
  given "a VIP customer"
  and "given they have at least 3 items totaling over $30"
  when "they proceed to checkout"
  then "they should receive a 10% discount"
} 

Of course, from here, stakeholders, through a collaborative effort, realize more scenarios are possible– for instance, the VIP customer has 3 items totaling over $100– thus, a higher discount is applied. A first stab of staying WET (that is, wholly expressing your tactics, man) yields this scenario:

scenario "VIP customer with 3 items, over $100 receiving 15% discount", {
  given "a VIP customer"
  and "given they have at least 3 items totaling over $100"
  when "they proceed to checkout"
  then "they should receive a 15% discount"
} 

Reading these scenarios (which are executable, by the way!) leaves no room for missing the boat– the tactics involved are wholly expressed!!– reading them is somewhat effortless from the standpoint that you don’t necessarily need to jump around the file to gain a clear understanding of context.

If you prefer staying DRY, the story can become more concise–

before_each "a VIP customer with 3 items is assumed", {
  given "a VIP customer"
  and "given they have at least 3 items"
}

scenario "VIP customer with 3 items, over $30 receiving 10% discount", {
  given "the 3 items total at least $30"
  when "they proceed to checkout"
  then "they should receive a 10% discount"
} 

scenario "VIP customer with 3 items, over $100 receiving 15% discount", {
  given "the 3 items total at least $100"
  when "they proceed to checkout"
  then "they should receive a 15% discount"
} 

Both stories convey intent– it is just that the WET one is more clearly expressed– in the DRY example, as more and more scenarios are added (and they surely will), one needs to jump to the top to gain an understanding of the underlying assumption (that is, a VIP customer with 3 items in their shopping cart).

DRY is fundamentally a sound principle– I’m not here to deny that; however, like all good things, it can be overused without regard for a particular situation. In fact, Johann Wolfgang von Goethe (of Faust fame, baby) is quoted thus:

“The phrases that men hear or repeat continually, end by becoming convictions and ossify the organs of intelligence.”

Because it is everyone’s bag, baby, think through DRYness from time to time and realize that in some cases, it is perfectly acceptable to WET yourself (I mean, to practice WET). Can you dig it, man?

I also blog at testearly.com | My company is hiring gurus

Expert Panel at Agile Experience
Posted By: Neal Ford on Tue. Jul. 1, 2008

Last weekend, I spoke at the Agile Experience in Reston. It was a great conference, lots of interesting topics, and a different crowd than most technical conferences. Half the attendees were managers, and everyone was enthused about Agile development. The experience level with Agile was diverse too, so it was fun to get out-of-the-blue questions. My first talk was Real-World Agile, and I start that talk by soliciting the agenda from the crowd (I open up a text editor and make the group tell me what they want to talk about). That was great here because it let me understand the actual pain points for the attendees, and it makes for a more interesting presentation for me.

On Friday night, we had a wide-ranging expert panel discussion which ranged from methodology to soft skills to cultural fit. And it was recorded. Come hear me stereotype all Americans as assholes!

Testing Anti-Patterns: Overspecification
Posted By: Jason Rudolph on Tue. Jul. 1, 2008

Tests increasingly serve multiple roles in today’s projects. They help us design APIs through test-driven development. They provide confidence that new changes aren’t breaking existing functionality. They offer an executable specification of the application. But can we ever get to a point where we have too much testing?

Enough is Enough

Consider the following test that you might come across in an application with a less-than-ideal test suite. (We’ll pick on some badly-written Rails code for this example, but the ideas we’ll discuss are certainly not unique to just Rails or Ruby or even just to dynamic languages. Unfortunately, these problems are quite universal.)

  1. require File.dirname(__FILE__) + ‘/../test_helper’
  2.  
  3. class ProductsControllerTest < ActionController::TestCase
  4.   def test_something
  5.     product = Product.create(:name => "Frisbee", :price => 5.00)
  6.     get :show, :id => product.id
  7.     assert_response :success
  8.     product = assigns(:product)
  9.     assert_not_nil product
  10.     assert product.valid?
  11.     assert product.name == "Frisbee"
  12.     assert product.price == 5.00
  13.   end
  14. end


Whoa! That sure is a lot going on in a single test case. What exactly is it that we’re trying to test here? Let’s take a step back and see if we can figure it out. [1]

  • Line 5 - We start off by creating a new product. We give the product a name and a price and call #create. Since we’re in a Rails app, without looking elsewhere in the code, we can make an educated guess that Product is an ActiveRecord subclass and that calling #create will persist the product to the database.
  • Line 6 - We send an HTTP GET request to a #show method and pass along the ID of the product we just created. Since we’re in ProductsControllerTest, we can safely infer that we’re calling the #show action in the ProductsController class.
  • Line 7 - We assert that the controller action responded with HTTP status code 200 (i.e., success).
  • Lines 8-9 - We look for an object stored in the assigns hash (i.e., the hash of variables that will be available to the view template) with a key of :product and we assert that it’s not nil.
  • Line 10 - We verify that the product object satisfies all the product validation rules (though we can’t know what those rules are without taking a look at the Product class).
  • Lines 11-12 - We assert that the attribute values we provided when creating the product (in line 5) match the attribute values stored in the object we fetched from the assigns hash.

For a class called ProductsControllerTest, it sure feels like we’re doing a fair bit more than just testing the code we’d expect to find in ProductsController (assuming ProductsController conforms to the traditional responsibilities of a controller). Let’s take a look at the controller code to better understand exactly what it is that we’re testing.

  1. class ProductsController < ApplicationController
  2.   def show
  3.     @product = Product.find(params[:id])
  4.   end
  5. end


It turns out that our controller code is notably simpler than our test case would have led us to believe. The #show action does indeed stick to the expected behavior of a controller, and in this case, it’s able to provide that behavior in a single line of code (despite the 8 lines of test code currently employed above). That single line satisfies all of the expectations of the #show action: look up the product with the given ID and place the product object in an instance variable for use by the view.

If the #show action isn’t responsible for knowing how to successfully save a new product record into the database, why does our test case attempt to provide the data for creating a new product? What will happen to our test case when someone adds a new validation rule requiring that all products also include a quantity attribute? Unfortunately, the test as it’s currently written will break. And while a failing test is often a welcome warning that our changes have inadvertently broken a part of our application, it’s far from desirable for a model-level rule related to creating new records to cause a failure in a controller test related simply to displaying existing records. In short, we’ve given our test case too much responsibility, and in doing so, we’ve made it fragile.

We can see from the #show action above that not only is the controller not responsible for knowing how to create a valid product, it’s also not responsible for ensuring that a product’s attributes are properly populated when the record is read from the database. However, if we take another look at the last few lines of the test case, we might think otherwise. That brings us to the second problem with this particular test: it’s a rotten source of documentation for the code being tested. As we increasingly move toward tests as specifications of our application’s behavior, it’s vital that those specifications clearly communicate the expected behavior. As it’s currently implemented, the overspecification in this test case leaves the reader having to do way too much work to figure out the true expectations of the code being tested.

Communicate Essence

Let’s take another pass at writing a test for the #show action, this time with an eye toward removing the fragility of the previous test case and increasing the value of the test as a specification.

  1. require File.dirname(__FILE__) + ‘/../test_helper’
  2.  
  3. class ProductsControllerTest < ActionController::TestCase
  4.   def test_should_show_product
  5.     product = create_product
  6.     get :show, :id => product.id
  7.     assert_response :success
  8.     assert_equal product, assigns(:product)
  9.   end
  10. end


In this implementation, we’ve abstracted away the logic for creating a new product in line 5. We’ve defined a helper method for use by any and all tests in our application that have a need to create a new product. If and when the rules for successfully creating a new product change, we’ll update the #create_product method, and we won’t have to touch the code in ProductsController or ProductsControllerTest at all. [2]

As for the four assertions that appeared at the end of our first attempt at this test case, we’ve replaced those assertions with a single (stronger) assertion. Where we previously asserted that the assigns hash held a non-nil product, that the product was valid, and that its attributes matched the attributes used at the beginning of the test, we now simply verify that the product object in the assigns hash is equal to the product object that we created at the beginning of the test. That single line more accurately and more concisely expresses our expectation: that the product whose ID we provide in the request to the #show action is the same object that’s made available to the view.

By focusing our test case on the essence of the code under test, we’ve ended up with less test code to maintain. And with the extraneous setup and assertions removed, the remaining test code provides a clearer and less fragile specification of the behavior being tested. [3]

May I Take Your Order, Please?

In the previous example, we might have detected the overspecification by the significant mismatch between the lines of test code and the lines of production code, or seeing model-specific assertions in a controller-specific test may have caught our eye. But, overspecification comes in more subtle forms as well. Consider the following method provided by ActiveRecord::Base for fetching the list of columns that hold domain-specific content from a model class in Rails.

  1. # Returns an array of column objects where the primary id, all columns ending in "_id" or "_count",
  2. # and columns used for single table inheritance have been removed.
  3. def content_columns
  4.   @content_columns ||= columns.reject { |c| c.primary || c.name =~ /(_id|_count)$/ || c.name == inheritance_column }
  5. end


To test this method, we’ll need a sample ActiveRecord model class. Let’s use the Topic model, which is backed by the following table.

  1. create_table :topics, :force => true do |t|
  2.   t.string   :title
  3.   t.string   :author_name
  4.   t.string   :author_email_address
  5.   t.datetime :written_on
  6.   t.time     :bonus_time
  7.   t.date     :last_read
  8.   t.text     :content
  9.   t.boolean  :approved, :default => true
  10.   t.integer  :replies_count, :default => 0
  11.   t.integer  :parent_id
  12.   t.string   :type
  13. end


In our first attempt at testing the #content_columns method, we might come up something similar to this:

  1. # (Naive) First Attempt
  2. def test_content_columns
  3.   content_columns      = Topic.content_columns
  4.   content_column_names = content_columns.map {|column| column.name}
  5.   assert_equal %w(title author_name author_email_address written_on bonus_time last_read content approved), content_column_names
  6. end


Can you spot the overspecification? To give you a hint, compare that test to the actual test employed in the ActiveRecord test suite:

  1. # The Real Deal
  2. def test_content_columns
  3.   content_columns        = Topic.content_columns
  4.   content_column_names   = content_columns.map {|column| column.name}
  5.   assert_equal 8, content_columns.length
  6.   assert_equal %w(title author_name author_email_address written_on bonus_time last_read content approved).sort, content_column_names.sort
  7. end


If you’ve ever written a test for something that returns an ordered list of items where the actual order either doesn’t matter or isn’t guaranteed, you’ve probably been bitten by this breed of overspecification, and there’s a good chance your solution matched the solution used in the ActiveRecord test code above. Because the #content_columns method doesn’t guarantee that the columns will be returned in any particular order, it’s inappropriate (and fragile) for our test to specify a certain order.

While the actual ActiveRecord solution above works, it too could be better. First, since we know that the two arrays in line 6 won’t be equal unless they have the same length, we can safely remove the extraneous length assertion in line 5. Second, when we see the calls to #sort on line 6, we’re forced to pause (if even for just a moment) to think about why it might be important to sort the two arrays. We don’t really want to sort the arrays; we’re just using that technique to get around the fact that order doesn’t matter to us, but it does matter when Ruby compares two arrays for equality. Since we really only want to assert that the arrays have the same elements, why not do exactly that?

  1. # Don’t Make Me Think
  2. def test_content_columns
  3.   content_columns        = Topic.content_columns
  4.   content_column_names   = content_columns.map {|column| column.name}
  5.   assert_same_elements %w(title author_name author_email_address written_on bonus_time last_read content approved), content_column_names
  6. end


By using an assertion like Shoulda’s assert_same_elements method, our test can clearly and concisely express the expected behavior.

Use It Wisely

Overspecification comes in many flavors, and the examples above in no way represent a comprehensive list. As developers, we frequently strive to write as little code as possible to accomplish the task at hand. When it comes to writing tests, we should very much keep that goal in mind as well. Good tests communicate the essence of the scenario being tested and nothing more. While I doubt a project will ever suffer from too much testing, it can certainly suffer from tests that specify too much.

Notes

[1] If this test seems absurd to you, good! Your ability to detect this type of overspecification will serve you well.

[2] The actual implementation of the #create_product method isn’t particularly pertinent in this discussion. (In the Rails space, there’s certainly no shortage of options.)

[3] With all the excessive thoroughness that went into overspecifying the the current behavior of the #show method, is it possible that we’ve been too distracted to identify other functionality that’s still missing from that method? In the next post, we’ll take a look at overspecification’s more lethargic cousin: underspecification.

Thanks to Justin Gehtland, Muness Alrubaie, and Glenn Vanderburg for reading drafts of this post.

easyb 0.9 hits the streets
Posted By: Andrew Glover on Mon. Jun. 30, 2008

announcement!
The easyb team is pleased to announce the release of easyb 0.9, baby!

The 0.9 release has:

easyb supports capturing additional hip information regarding stories, such as a story’s description and some detail regarding the features, benefits, and roles of a persona related to a story. For instance, the DSL now supports a description syntax that takes a String value — single quote or Groovy’s triple quote trick.

description "some description"
scenario "text"

or

description """some long description that requires
multiple lines, etc
"""
scenario "text"

What’s more, you can provide additional details of a story via the narrative syntax:

description "text"

narrative "description", {
 as_a "role"
 i_want "feature"
 so_that "benefit"
}

scenario "text"

Both the narrative and description keywords are optional and they don’t have to be used together– i.e. you can use the narrative one without providing a description. These aspects will be captured in the output (i.e. story report) of an easyb run too.

From a fixture standpoint, easyb supports both one time fixtures (before) and for each scenario (before_each). Of course, you can add tearDown-like behavior in after and after_each.

You can download the latest release from easyb’s Google code page.

I also blog at testearly.com | My company is hiring gurus

Ruby in the Enterprise: eRubyCon
Posted By: Jared Richardson on Mon. Jun. 30, 2008

For those of you who are wondering if Ruby is enterprise worthy, then eRubyCon is for you. The speaker list is a "Who's who" of Ruby development and a stellar slate for any conference.
If you're into Ruby or Rails, I strongly encourage you to check out this event.

eRubyCon.com

Continuous Integration: Fewer Bugs, Less Work
Posted By: Jared Richardson on Sun. Jun. 29, 2008

Jennette Mullaney was kind enough to attend my talk Continuous Integration, The Cornerstone of a Great Shop talk in Las Vegas. We spoke for a bit afterwards and she put it all together into a nice interview.

Continuous integration reduces bugs, increases productivity

Enjoy!

The weekly bag– June 27
Posted By: Andrew Glover on Sun. Jun. 29, 2008

I also blog at testearly.com | My company is hiring gurus

GraphicsBuilder: Substance based filters
Posted By: Andres Almiray on Sun. Jun. 29, 2008

Continuing with the Substance related additions, it is now possible to use Fractal Flames as texture filters. I was very impressed by Kirill's demo on Fractal Flames, even wanted to add them to GraphicsBuilder ASAP. Well it took a bit longer than that but now it is done. Check it out


Fractal Flames require SubstanceColorSchemes in order to work, you can reference a predefined one using smart builder variables, like limeGreenColorScheme (which is actually an instance of LimeGreenColorScheme); you may also use the colorScheme node, which will automagically translate its value into a predefined SubstanceColorScheme. The following are equivalent calls for obtaining a LimeGreenColorScheme
  • colorScheme( "limeGreen" )
  • colorScheme( "lime green" )
  • colorScheme( "lime_green" )
  • colorScheme( "LIME GREEN" )
As Kirill notes, generating a fractal flame is a costly operation, depending on the number of iterations and the type of function (IterativeFunctionSystem) that you use to generate them. This filter will try its best to keep a cached result of the generated fractal, calculating it again only when a visible property has changed value.

Keep on Groovying!

GraphicsBuilder: More Shapes!
Posted By: Andres Almiray on Sat. Jun. 28, 2008

Kirill has been busy lately updating Substance with new features, a recent post on his blog shows button shapers in action. Suddenly realized that supporting those shapes in GraphicsBuilder would be quite easy, and so graphicsbuilder-ext-substance was born. Here is a sample image



Once the shapers were wrapped with a ShapeGraphicsOperation (actually just one shaper was required) the rest of the work was just wiring property aliases. Here is the code that produced the image

You can find other goodies in the Substance Extras pack, like fractal flames. Imagine a filter based on those :-D

Keep on Groovying!

JMatter-20080627 released
Posted By: Andres Almiray on Fri. Jun. 27, 2008

JMatter 20080627 has been released [changelog,download]

I haven't given a full review to this release yet (hot from the oven a couple of hours ago!) but skimming through the release notes I noticed this gem
support for easy custom uis/layouts using abeille form designer (this replaces previous autolayout mechanism based on abeille; it didn't work very well; docs and examples to follow)

I have to try that! Abeille Forms Designer is a GUI builder for Java applications, that leverages the power of JGoodie's FormLayout.

Congratulations to Eitan for his continued efforts in pushing the limits with JMatter, also to all contributors (there are two user submitted patches in this release!) and other JMatter users that have provided feedback. Keep those messages coming!

Book Review: Beginning Java SE 6 Platform
Posted By: Andres Almiray on Fri. Jun. 27, 2008

I've been reading Jeff Friesen's Beginning Java SE 6 Platform, From Novice to Professional for a couple of weeks now. I thought that David Flanagan's "JavaNut" series form O'Reilly were the best sources to learn Java and get up to speed with changes from each Java release, boy was I for a surprise with Jeff's book.

Even though the title mentions Beginning and Novice you will not find an introduction to Java on it, as a matter of fact not even a Java5 introduction. Jeff assumes you have good knowledge of Java5 and jumps right into Java6, which IMO makes it a "deal breaker", you will be able to review and learn Java6 only features. Every feature comes with a little bit of history of why it was added to Java6, almost every one comes with a code sample, allowing you to test it right away (I was sure to fire up a copy of good 'ol Groovy console as I read the book :-D Groovy's console is great for quick prototyping of Java code). But what really makes this book shine is that Jeff has included notes on every single JSR involved, every single bug filed and resolved for Java6, he also includes links to articles, papers, blog posts and online discussions on why those features were needed, or how to make the most of them.

The book organizes Java6's features in logical sets of behavior, sorted alphabetically
  • Core Libraries
  • GUI Toolkits: AWT
  • GUI Toolkits: Swing
  • Internationalization
  • Java Database Connectivity
  • Monitoring and Management
  • Networking
  • Scripting
  • Security and Web Services
You can bet I played with all the features explained in the GUI Toolkit chapters :-) (adding TrayIcon/SystemTray support to Swing applications is dead easy now). Though I'm not into JMX nor Web Services (yuck ;-)) those chapters made me consider giving those technologies another look. I'm very happy with this book, I know where I will be looking when stuck with a Java6 feature.

Communication Channels & Cell Phones
Posted By: Neal Ford on Fri. Jun. 27, 2008

I noticed the other day that lots of states now ban talking on cell phones while driving, yet they don���t outlaw talking to a person sitting on the seat next to you. Why is that? I have a suspicion: talking to someone on a cell phone takes a lot more concentration. Many studies place accident rates for drunk drivers and cell-phone talkers evenly. The implication is that talking on your cell phone robs you of as much concentration as drinking!

But my experience with software development bears this out. I���ve worked on several geographically diverse projects, where the communication channel is reduced to phone calls in conference rooms. This is a terrible communication medium because you can���t see the other people, can���t see their facial expressions and body language, and don���t understand the subtleties of their vocal inflections. Humans are social animals (even developers who don���t interact well with other humanoids). We don���t realize how much we rely on those non-verbal communication channels until we notice how much concentration it takes to talk on a cell phone in a car.

Alistair Cockburn has a great diagram in his book Agile Software Development.

Temperature of Communication Channels

He has modeled communication effectiveness to temperature dispersal from a heating source. The further away from the source, the colder you are. This is a great metaphor because it takes into account the subtle communication channels upon which we depend but don���t realize are there until they���re not.

The importance of this for software development shouldn���t be ignored. If you engage in distributed development, insist on warmer communications, like video conferencing. Even Skype video, while crude sometimes, beats the phone-call-in-crowded-conference-room anti-pattern. On one of my projects, we had serious cross-ocean communication gaps because we���d never met in person. The results aren���t surprising: personality clashes, misunderstanding about technical problem resolution that cost us time, and general stand-offishness between the teams. Wisely, my project manager invoked the XP ���Move people around��� principle, and we shuffled developers from the US to India and vice-versa, for a couple of iterations each. This was on a fixed-bid project, so we incurred the cost for the travel ourselves. And it was the best thing that ever happened to the project. Once you���ve met people and spent time with them, it makes even conference call communication better, because you can pick up on subtle clues in people���s voices that indicate a facial expression you���ve seen for yourself. One of the developers on our US team was widely loathed by the developers in India (so much so that, when I went there, they had drawn an ���X��� over his face in the team photo we had on the wall!). But, when he went there himself, he became fast friends with many of the developers. Some personalities must be experienced in person before they are tolerable, especially to different cultures.

So, the next time you are driving and talking on your cell phone, do 2 things: keep an eye out for the police in your rear view mirror, and notice how much more mental energy it takes to talk on the phone rather than to a person sitting with you. This to me is the proof that Cockburn nailed it.

What happened to the applet?
Posted By: Andrew Glover on Wed. Jun. 25, 2008

It’s clear that the initial bogue bet on Java’s ubiquity in the browser, in the form of applets, never paid off– history, however, has shown that Java found its foothold on the server-side. Nevertheless, because it’s everyone’s bag, applets are still around as I run into them from time to time. Interestingly, Sun has been putting some effort into underlying engine that runs applets (the Java plug-in), which begs the question– are applets still alive? What’s more, if they aren’t (or are on life support as some have suggested), what happened to them?

Richard Monson-Haefel recently pointed me to an hip conversation with everyone’s favorite disco superstar, Ted Neward (who you may have heard blather on and on (and on!) about Scala recently) who yammers (on and on and on– in reality, only 15 minutes but they do cut him off as he’s chattering on and on and on!) about why he thinks applets effectively kicked the bucket.

Just the same, Sun hasn’t thrown in the towel! In fact, not long ago, I had the privilege of conducting a dialog with Ken Russell, a Sun engineer focused on rebuilding the Java plug-in. According to Ken, applets aren’t dead yet and are a compelling platform for building Rich Internet Applications.

Both conversations are appealing in that they shed some light on the lessons learned about Sun’s initial applet bet and where the future may be headed (regardless if applets will be with us or not). For me, I’m not sure applets are dead just yet– Ken gave me reason to believe otherwise. Have a listen to both Ted Neward and Ken Russell and decide for yourself, man!

I also blog at testearly.com | My company is hiring gurus

Groovy Fun With ObjectRange
Posted By: Scott Leberknight on Wed. Jun. 25, 2008

I ran into a situation the other day with Groovy that baffled me at first. Let's create a range from 0.0 to 10.0 and then use it to check if a certain number is contained within that range, like this:

groovy:000> r = 0.0..10.0
===> 0.0..10.0
groovy:000> r.contains(5.6)
===> false

WTF? The number 5.6 is not contained in the range 0.0 to 10.0? I beg to differ. So what's actually going on here? Using the shell we can do some more digging, interrogating the range object to see what its bounds are, what values it contains if you iterate it, and so on:

groovy:000> r = 0.0..10.0
===> 0.0..10.0
groovy:000> r.class
===> class groovy.lang.ObjectRange
groovy:000> r.from.class
===> class java.math.BigDecimal
groovy:000> r.to.class
===> class java.math.BigDecimal
groovy:000> r.each { print " $it " }  
 0.0  1.0  2.0  3.0  4.0  5.0  6.0  7.0  8.0  9.0  10.0 ===> 0.0..10.0
groovy:000> r.contains 5 
===> true
groovy:000> r.contains 5.0
===> true
groovy:000> r.contains 5.6
===> false

So what did we learn? First, the range is an ObjectRange whose bounds are BigDecimals. Second, that iterating by default iterates in increments of one. And third that the contains method does not quite do what I would expect by default. Looking at Groovy's ObjectRange class makes it clear exactly what's going on, so let's look:

public boolean contains(Object value) {
  Iterator it = iterator();
  if (value == null) return false;
  while (it.hasNext()) {
    try {
      if (DefaultTypeTransformation.compareEqual(value, it.next())) return true;
    } catch (ClassCastException e) {
      return false;
    }
  }
  return false;
}

The Groovy ObjectRange's contains method defines containment as whether a value is contained within the values generated by its iterator. By now many of my many millions of readers are about to post a comment telling me the problem, so I'll preempt that temptation by adding a few more lines of interaction with the Groovy shell:

groovy:000> r.containsWithinBounds 5.0
===> true
groovy:000> r.containsWithinBounds 5.6
===> true

Aha! So contains doesn't do what you might think it should, but containsWithinBounds does. Its JavaDoc says "Checks whether a value is between the from and to values of a Range." Conspicuously there is no JavaDoc on the contains method to tell me that what it actually does is check whether a value is contained within the discrete values generated by the iterator. Let's try more more thing:

groovy:000> r.containsWithinBounds 5
ERROR java.lang.ClassCastException: java.lang.Integer
        at groovysh_evaluate.run (groovysh_evaluate:2)
        ...

Oops! Not only do you need to call containsWithinBounds rather than contains, you also need to call it with the correct type, as there is no coercion going on since it uses Comparable.compareTo() under the covers.

Notwithstanding all the recent activity regarding all the Ruby security flaws recently discovered, how does Ruby handle inclusion of a number within a range? Here's some irb output:

>> r = 0.0..10.0
=> 0.0..10.0
>> r.class
=> Range
>> r.begin.class
=> Float
>> r.end.class
=> Float
>> r.each { |item| print " #{item} " }
TypeError: can't iterate from Float
        from (irb):53:in `each'
        from (irb):53
>> r.include? 5
=> true
>> r.include? 5.0
=> true
>> r.include? 5.6
=> true

To me this is more semantically and intuitively correct behavior. First, while I can create a range with float bounds, I cannot iterate that range - for non-integral numbers, how exactly can you define the next item after 0.0 for example? 0.1, 0.01, 0.001, and so on till infinity. Second, the include? method behaves as I would expect no matter what type of argument I pass. I am able to iterate ranges of integral numbers, however, which could arguably also be confusing since the behavior of the method depends on the type. Then again, that's pretty much what polymorphic method behavior is about I suppose.

>> r = 0..10
=> 0..10
>> r.each { |item| print " #{item} " }
 0  1  2  3  4  5  6  7  8  9  10 => 0..10

In the case of integers Ruby uses an increment of one by default. You could use the step method to get a different increment, e.g.:

>> r.step(2) { |item| print " #{item} " }
 0  2  4  6  8  10 => 0..10

So what's the point of all this? That Ruby is better than Groovy? Nope. I really like both languages. I think there are a couple of points that were reinforced to me:

First, RTFM (or source code --> RTFC). Even though Groovy's contains method doesn't behave how I think it should, there is the method I was looking for with containsWithinBounds.

Second, having a shell to play around with short snippets of code is really, really useful, without needing to create a class with a main method just to play around with code.

Third, documentation and semantics matter. If something doesn't feel intuitively correct based on how similar things act, it is more likely to cause confusion and errors. In this case, since my unit test immediately caught the error, I was able to figure the problem out in a few minutes.

Finally, following on from the last point, unit tests continue to remain valuable. Of course anyone who knows me would roll their eyes over my anal-ness (which Mac's dictionary is telling me is not really a word but I don't care at the moment) expecting me to get something about unit testing in somehow.

PAD among top books
Posted By: Venkat Subramaniam on Tue. Jun. 24, 2008

This morning I got an email

"I thought you might get a kick to see that your (and Andy���s) book was named one of the Top 100 Software Engineering books of all time (#49).  They determined it based on variables, such as Amazon rank and number of Jolt awards, etc.
 
The article is up on dotnetkicks or the direct link is http://www.noop.nl/2008/06/top-100-best-software-engineering-books-ever.html.
 
Congratulations,
Zach"


Thanks Zach. It is not only nice to see PAD appear in the list (among other excellent Pragmatic Bookshelf books), but nice to see a list of good books in one place for those interested in learning and keeping up.
Speaking of which, I can't wait to be at AgileIT X. There will be some great speakers there and several exciting topics. I am looking forward to give five talks and workshop, but also listening and discussing with others who will be there. Can't wait for Thursday.

The IT conference you can't miss if you're in Paris!
Posted By: Guillaume LaForge on Tue. Jun. 24, 2008

If you're in Paris, next week, make sure you don't miss the "Université du SI" (IT University) conference, organized by my former colleagues from OCTO Technology. This conference is going to rock! Quite frankly, I think France was seriously lacking a good IT conference, and I think OCTO is going to deliver on that promise. I've been told they are pretty soon running out of entry passes as we're close to the deadline, so it's your last chance to register.

If you want to hear Neil Armstrong speak about how he went to the moon, listen to a famous French philosopher, hear what C++ inventor Bjarne Stroustrup has to say, you've knocked at the right door. The line-up of speakers is pretty impressive. The various presentations cover a wide range of very interesting topics, under 4 main categories:

  • Architecture,
  • IT Governance,
  • Methodologies, and
  • Technologies.

I'll personally have the pleasure and honor to also speak there, and will cover my two pet topics: Groovy and its ability to let you write Domain-Specific Languages, and Grails for helping people be more productive when developing business apps.

Here are the abstracts of my two talks (in French, I'm sorry!):

  • Les Domain-Specific Languages avec Groovy
    Les Domain-Specific Languages sont des artifacts architecturaux à la mode, comme l'indiquait récemment un rédacteur sur InfoQ. Avec les langages dynamique tels que Groovy, il est aisé de créer un mini-langage modélisant un domaine d'expertise particulier. Grâce à ces DSLs, développeurs et experts métier seront capable de partager une métaphore commune, de délivrer, main dans la main, l'application aux utilisateurs finaux. Groovy offre un niveau élevé de flexibilité en termes d'expressivité et de concision de sa syntaxe et au travers de sa nature de langage dynamique. Après une introduction aux concepts de DSLs et leur motivation, Guillaume Laforge, chef de projet de Groovy et spec lead du JSR-251 standardisant le langage Groovy, vous guidera au travers des concepts avancés de Groovy vous permettant de créer votre propre mini-langage métier. Il vous montrera comment intégrer ces langages dans vos applications Java EE, et expliquera également comment au mieux définir ces langages métier, pour s'assurer leur adoption par les utilisateurs finaux, leur qualité, leur testabilité, et leur capacité à évoluer au cours du temps pour répondre au mieux aux besoins du jour, ` toujours en perpétuelle évolution.

  • T18 - Innover sans contraintes, intégrer sans ruptures
    Le business case est innovant et les contraintes métier imposent des délais serrés... Pour répondre à ce besoin, il existe des solutions open-source "intégrées" permettant d'être très rapidement opérationnel et d'accélérer les développements. Comment favoriser l'innovation sans contraintes et garantir une intégration sans rupture dans le S.I dans le respect de ses normes et standards !? Retour d'expérience sur Grails, framework de développement d�applications Web sur la JVM.

Just How Does Spring Do Its Classpath Component Scanning Magic?
Posted By: Scott Leberknight on Mon. Jun. 23, 2008

One really cool feature in Spring 2.5+ is classpath component scanning. For example, instead of manually defining and wiring up all the beans comprising your Spring-based application, you simply add a few "driver" snippets of XML to your application context configuration, and then annotate your component classes with @Component (or any specialization such as @Controller and @Service). I am calling the XML snippets a "driver" because all they do is enable a specific feature, such as classpath scanning or component autowiring:

<-- Enable autowiring via @Autowire annotations -->
<context:annotation-config/>

<-- Scan for components in a package (and its subpackages)  -->
<context:component-scan base-package="org.springframework.samples.petclinic.web"/>

After seeing this was pretty cool, I wanted to know how exactly they did the classpath scanning. It boils down to doing some gymnastics with class loaders and resource path matching and using the ClassLoader.getResources(String name) method which returns an Enumeration containing URLs representing classpath resources. Those resources (Java classes) are then checked to see if they contain the @Component annotation (or a specialization of it) and if so, are considered a "candidate" component. Other filtering can take place but by default those components are then defined programmatically as Spring beans. When annotation configuration is enabled, autowiring of components also takes place, so I can have Spring scan the classpath for all my web controllers, and then automatically inject dependencies such as services or data access objects. Cool!

The actual classes that perform this magic are the ClassPathScanningCandidateComponentProvider which, by default, uses a PathMatchingResourcePatternResolver to find matching classpath resources using ClassLoader.getResources(). As a quick example, you can see this in action by writing a simple script, like so:

ClassPathScanningCandidateComponentProvider provider =
    new ClassPathScanningCandidateComponentProvider(true);
String basePackage = "org/springframework/samples/petclinic";
Set<BeanDefinition> components = provider.findCandidateComponents(basePackage);
for (BeanDefinition component : components) {
    System.out.printf("Component: %s\n", component.getBeanClassName());
}

Running this code (using the PetClinic sample application shipped with Spring), you get the following output:

Component: org.springframework.samples.petclinic.hibernate.HibernateClinic
Component: org.springframework.samples.petclinic.jdbc.SimpleJdbcClinic
Component: org.springframework.samples.petclinic.jpa.EntityManagerClinic
Component: org.springframework.samples.petclinic.web.AddOwnerForm
Component: org.springframework.samples.petclinic.web.AddPetForm
Component: org.springframework.samples.petclinic.web.AddVisitForm
Component: org.springframework.samples.petclinic.web.ClinicController
Component: org.springframework.samples.petclinic.web.EditOwnerForm
Component: org.springframework.samples.petclinic.web.EditPetForm
Component: org.springframework.samples.petclinic.web.FindOwnersForm

For a more fun experiment, I tried to scan using "org" as the base package...

Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
	at org.springframework.asm.ClassReader.a(Unknown Source)
	at org.springframework.asm.ClassReader.(Unknown Source)
	at org.springframework.core.type.classreading.SimpleMetadataReaderFactory.getMetadataReader(SimpleMetadataReaderFactory.java:76)
	at org.springframework.core.type.classreading.CachingMetadataReaderFactory.getMetadataReader(CachingMetadataReaderFactory.java:68)
	at org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider.findCandidateComponents(ClassPathScanningCandidateComponentProvider.java:181)
	at org.springframework.samples.petclinic.ClassPathScannerTester.main(ClassPathScannerTester.java:17)

Ok, so you need to restrict the scan space that Spring will use or else you could run out of memory scanning every possible class in your system! Regardless, with classpath scanning of components and autowiring of dependencies, you can cut down the amount of XML in Spring-based apps a lot.

Generics in Java
Posted By: Venkat Subramaniam on Fri. Jun. 20, 2008

I have talked and written about my opinions on Java Generics before> (I love Generics in .NET, but that love does not extend to the implementation in Java).

Type information is useful at times, and I like for a way to infer that information. Generics provide that, but is too heavyweight of an approach and also leads to an illusion of type safety when it provides none. If all we care about is type information, there's gotta be a better way to realize that.

Brian gives a good example where having the type information can be useful���How Generics can pay dividends. But, is that a dividend or is it a tax allowance? Are Generics the best way to get type information/type inference or should there be a lightweight, better way?

Grails Plugin For Hudson
Posted By: Jeff Brown on Thu. Jun. 19, 2008

I am pleased to announce that we have worked up a Grails plugin for Hudson. Hudson is a really slick continuous integration server. Check out their site for more info on the engine itself.

It has always been possible to build Grails apps from Hudson but in the past this has involved writing shell scripts that are triggered by Hudson. This works but is not the slickest solution. What you really want is for the CI server to have knowledge of the fact that the project you are building is a Grails app and that knowledge will allow the tool to be more efficient about carrying out the build and also allow the CI server to provide Grails specific options for the build. This is where the new Grails plugin is heading.

Right now the plugin is very basic. In the system configuration screen you may configure as many Grails installations as you like. This is useful for situations where the same CI server may be building multiple projects with different version of Grails or maybe even building multiple copies of the same project with multiple versions of Grails. Below is a screenshot of the system configuration screen:



Notice that there is built in validation to make sure you have entered a valid path to your Grails installation.

When configuring a project in Hudson you have a lot of options for what should happen at build time. The Grails plugin adds a "Build With Grails" option and if that option is selected you can select from a list of common build targets to execute as well as type in any arbitrary targets you may want to execute. This is useful for executing Grails commands that are not in the list of checkboxes and for executing your own custom Grail scripts that may be part of your project. Below is a screenshot of the project configuration screen:



The first version of the plugin has not been released yet but will be soon. In the meantime, I would be happy to hear what kinds of capabilities you would like to see the plugin provide. Even in its current very basic state, the plugin is very useful as it makes configuring a Grails project in Hudson drop dead simple.

Scala pimpin’ with Ted Neward
Posted By: Andrew Glover on Thu. Jun. 19, 2008

I recently had the opportunity to discuss Scala with my friend Ted Neward for JavaWorld’s Java Technology Insider. Ted’s been talking about Scala for quite some time now and he’s the person who turned me on to this compelling functional language.

In this conversation, Ted explains what functional programming is and why people should care– he’s got some interesting thoughts regarding OO languages versus functional languages and more importantly, where each paradigm is a good fit. Scala’s definitely got some interesting features– if you are curious to hear them, then have a listen, man!

I also blog at testearly.com | My company is hiring gurus

10 must-have Rails plugins
Posted By: Justin Gehtland on Wed. Jun. 18, 2008

I was talking to Tim the other day about auditing Rails projects, and how we see a lot of Rails projects that reinvent the wheel instead of using plugins. The obvious follow-up question, of course, is "What plugins (or gems) should we be using?" Below I list ten plugins that we use regularly, and a brief reason why you might want to, too.

  • fixture_replacement2: fixtures are difficult to maintain. There is no "one size fits all solution," but we have found this to be a big help.
  • tarantula: A single test can find a lot of bugs, if that single test visits every link in your app, tries to submit bad data, and polices your output HTML.
  • test_spec_on_rails: specs are better than tests.
  • permalink_fu: meaningful URLs for your objects.
  • safe_erb: don't trust external data!
  • unit_record: get the database out of your unit tests. 1000s of tests can run in seconds.
  • restful_authentication: clean, simple authn.
  • multi-rails: test your code against multiple versions of Rails in a single rake task.
  • attachment_fu: most apps need attachments eventually.
  • exception_notification: find out by email when things go wrong.

Many of these plugins have alternatives (e.g., you could use rspec instead of test_spec, or nulldb instead of unit_record). Regardless of which plugin you pick, make sure you think about the features provided by the plugins above, and don't reinvent the wheel.

Notice that most of these plugins are already in git, so forking them is easy. If you see something that needs improvement, jump in and do it! While reinventing the wheel is bad, improving the wheel is most welcome.

[6/18/2008: updated to include github url for fixture_replacement]

10 must-have Rails plugins
Posted By: Stuart Halloway on Wed. Jun. 18, 2008

I was talking to Tim the other day about auditing Rails projects, and how we see a lot of Rails projects that reinvent the wheel instead of using plugins. The obvious follow-up question, of course, is "What plugins (or gems) should we be using?" Below I list ten plugins that we use regularly, and a brief reason why you might want to, too.

  • fixture_replacement2: fixtures are difficult to maintain. There is no "one size fits all solution," but we have found this to be a big help.
  • tarantula: A single test can find a lot of bugs, if that single test visits every link in your app, tries to submit bad data, and polices your output HTML.
  • test_spec_on_rails: specs are better than tests.
  • permalink_fu: meaningful URLs for your objects.
  • safe_erb: don't trust external data!
  • unit_record: get the database out of your unit tests. 1000s of tests can run in seconds.
  • restful_authentication: clean, simple authn.
  • multi-rails: test your code against multiple versions of Rails in a single rake task.
  • attachment_fu: most apps need attachments eventually.
  • exception_notification: find out by email when things go wrong.

Many of these plugins have alternatives (e.g., you could use rspec instead of test_spec, or nulldb instead of unit_record). Regardless of which plugin you pick, make sure you think about the features provided by the plugins above, and don't reinvent the wheel.

Notice that most of these plugins are already in git, so forking them is easy. If you see something that needs improvement, jump in and do it! While reinventing the wheel is bad, improving the wheel is most welcome.

[6/18/2008: updated to include github url for fixture_replacement]

SVWeb-JUG: Jason van Zyl on Maven
Posted By: Andres Almiray on Wed. Jun. 18, 2008

The Silicon Valley Web JUG had its monthly meeting yesterday night, with guest speaker Jason van Zyl from Sonatype. Here is what JUG members received on their mailboxes before the talk
Comprehensive Project Intelligence ��� Apache Maven, Nexus, and m2eclipse

Many view Apache Maven in the context of other build tools such as Apache Ant and Apache Ivy, yet Maven's functionalities extend far beyond the efficient, enterprise-class project build. When coupled with supporting tools like Nexus and m2eclipse, Maven starts to accelerate development by reducing the level of work required to support build management and cross-department collaboration.

In this talk, Jason van Zyl, founder of Sonatype and creator of Maven's Central Repository, will present a constellation of open-source software which can be used to extend Maven's capabilities, from next-generation Eclipse support provided by m2eclipse to the Nexus Repository manager and continuous integration servers which offer Maven support. Jason will also introduce some of the more unexpected uses of Maven to support development with Flex and to support the publishing industry.

Jason did not disappoint. He not only showed Nexus running and its integration within Eclipse, but also the m2eclipse plugin (maven integration); Idiom, a template consumer for site documentation (think a better maven-site-plugin to start with); and another project (I can't recall the name right now) that lets you build OSGi bundles in the command line, that is right, no need to mess up with a running IDE, how cool is that?

Personally I really like the new level of integration between Maven and Eclipse. I use them both most of the times in my projects, keeping project dependencies in sync is always a hassle, but m2eclipse gets rid of all the cruft. Jason mentioned that one of the goals of the project is configure a maven enabled project without having to actually look at the POM in its XML form. Can't wait to test it.

Nexus looks also very promising, it may work as a proxy for all your repos in your organization, users just have to point to the the Nexus server. It also has a cool feature called routing tables. Think for a moment of that useful open source project you app depends on. You found a bug but the project's team can't/won't react as fast as needed, so you go with patch it yourself and run with the same groupId and versionId as you do not want to update the poms. It works, but it may break other teams in your organizations. So what routing tables do is filter out specific artifacts from specific sites, you may configure Nexus to serve all org.apache.commons artifacts from the official Apache commons repo and nothing else, leaving any in-house patches out of the equation. Definitely worth exploring.

Thanks to Jason for a great talk, Mike and Kevin for organizing the event and Google for hosting.

On a related note I met again with Sven Haiges (@hansamann) and recorded an interview for the Grails podcast. Though we talked shortly about Grails, he made me realize there may be a Grails plugin based on Json-lib. Good times.

Oh and another thing, Aaron Houston kick started the meeting by announcing that Mike is a brand new Java Community Champion, congrats!

Creating Executable JARs using the Maven Assembly Plugin
Posted By: Scott Leberknight on Wed. Jun. 18, 2008

On a current project I needed to create an executable JAR that does a bunch of processing on collections of files. As with most projects, I rely on a bunch of open source tools as dependencies. Since, to my current knowledge anyway, there is no way to have JARs within JARs I needed a quick way to create an executable JAR containing all the required dependencies. I did a bunch of searching and asking around and eventually found the Maven Assembly Plugin. This plugin generates "assemblies" which could be just the executable JAR or could be an entire source distribution in multiple formats (e.g. zip, tar.gz, etc.).

The basics of the plugin are simple. Add the <plugin> to your Maven POM file, define the assembly, and for executable JARs specify the main class. Here's how I configured the plugin:

<plugin>
  <groupId>org.apache.maven.plugins</groupId>
  <artifactId>maven-assembly-plugin</artifactId>
  <configuration>
    <descriptorRefs>
      <descriptorRef>jar-with-dependencies</descriptorRef>
    </descriptorRefs>
    <archive>
      <manifest>
        <mainClass>com.nearinfinity.arc2text.ARC2TextConverter</mainClass>
      </manifest>
    </archive>
  </configuration>
</plugin>

In the above, I used one of the conveniently predefined descriptor references, in this case "jar-with-dependencies" which does pretty much exactly as you would expect. You could also define your own assembly but that looked quite a bit more complicated and all I needed was to simply produce an executable JAR. When the assembly plugin executes the above example configuration, it creates a single executable JAR with all my classes and all the classes from all the dependencies. It also sets up the JAR manifest with the Main-Class that you specify. The dependencies, which in my case were all other JAR files, are extracted from their JARs and placed directly into the JAR file, i.e. the classes in the dependent JARs are extracted and then put into the new custom JAR. The plugin even copies over license files, e.g. LICENSE, ASM-LICENSE.txt, etc. into the META-INF directory in the JAR.

The only things left to do is use the plugin. To do that you can simply run the command:

mvn assembly:assembly

There are other goals in the assembly plugin but this is the main one you need. So if you need to create an executable JAR containing dependencies, this is a nice quick way to do it, especially if you were already using Maven.

Seoul Observations
Posted By: Neal Ford on Tue. Jun. 17, 2008

I have a cool job. The opportunity to travel to interesting places is one of the coolest parts. Recently, I had the chance to go for the first time to Seoul, Korea, speaking at the Entrue Developers Conference.The conference was very well organized, but it was a conference like any other. The interesting things for me were the observations I made while I was there.

First up, phones and Internet. I proudly carry an iPhone (one of the first purchasers, don't you know), and smugly rub it in the face of all the poor phone 1.0 owners. In Korea, their cell network is far more advanced than ours. So advanced, in fact, that they aren't even backwards compatible with our phones. None of my other co-worker's phones worked either, except the one that had a special phone for Korea. The other notable technology difference was the speed of the Internet connections. The Internet in my hotel room was one of the fastest I've ever used! Stuff that takes 45 minutes to download here takes 7 minutes in Seoul. Unfortunately, I didn't actually measure the speed, but it was blindingly fast. And that was just my hotel room connection!

Second, business in Seoul is much more formal than here. Before travelling there, I asked my co-worker from China meeting me there about the dress code. I try to remember to do that when I travel so that I minimize the ugly Americaness that leaks through anyway. He said "Oh, don't worry -- it's business casual. Slacks and button up shirt is fine." Well, I get there, and I'm the only one there without a suit. One of the nice things our host did for us was an invitation for a lunch with about 200 corporate CIO's in Seoul. My co-worker (the same one who advised me) leaned over and said "See that guy over there -- he isn't wearing a suit, so you aren't the only one." Thanks! In general, business is much more formal. Developers wear suits and ties to work, which is increasingly rare here.

Third, I was asked to give a presentation at one of the local companies, to their enterprise architecture group (SOA is big in Korea). The only snag: they don't speak english, and I don't speak Korean. The local guy there who invited me to speak at the conference volunteered to translate for me. This was a first: I would discuss the contents of a slide or example, then pause while he translated the entire thing to Korean. He was extremely knowlegable about technology, so I have high confidence in his translation. It was just weird: speak, pause, speak, pause...for almost 2 hours!

Fourth, they have different technology priorities there. While a lot of big companies in the US have embraced the run-away accidental complexity that is SOA, they have taken it to a manaical level. We sat through a presentation of an SOA Goverance Framework. They have every detail nailed down to the tiniest degree. It looked great on paper, but it was absolutely unworkable in the real world. Can you really tell the business that they must slow down their pace of innovation because the SOA goverance framework keeps all IT at a snail's pace? Developers spend more time filling out forms and consulting the thousands of pages of documentation on how to govern their SOA than they do actually writing code. I asked during the presentation how this impacts the business and got blank stares: business? What does the business have to do with our enterprise architecture? It was the most elaborate, meticulous, detailed, unworkable framework I've ever seen.

My fifth observation is the dichotomy of their IT priorities. On the one hand, they've embraced SOA (particulary the bad parts, in my opinion) whole-heartedly. The important priorities for their enterprise development seems to be to lock down all variability (and therefore flexibility, evolvability, and adaptability) from their enterprises. They have state of the art SOA fetish there, building meta-SOA frameworks. Yet, you ask them about some of the things considered interesting in the states (like the rise of dynamic languages), it's not even on their radar. It's not that they have looked at it and disregarded it. They haven't even heard of most dynamic languages. Ruby? Groovy? Python? The only one they've even heard of is Perl, and they have a poisionous disdain for it. They have of course heard of JavaScript, but it's a toy language for visual effects in browsers. They treat it like an extension of CSS.

Of course, the best part of traveling is the people: I met so many friendly, gregarious, funny, open people there. We had several great meals, lubricated either by fine wine or Soju, the Korean version of Sake. It's wonderful stuff: it tastes like mild Sake, but it packs almost the punch of vodka. We talked about lots of stuff, both technical and non-technical. The last speaker's dinner had geeks from Korea, the US, China, Japan, Singapore, Malyasia, and lots of other places. Travel does indeed broaden you, often in unexpected ways.

Rethinking the traditional DAO pattern
Posted By: Andrew Glover on Tue. Jun. 17, 2008

Back in the Age of Aquarius, a popular pattern emerged in the Java world dubbed “the data access object“, which essentially

“separates a data resource’s [hip] client interface from its data access mechanisms”

meaning that clients to a particular domain object were shielded from the actual implementation of communicating with a particular database. Provided that clients worked with the interface type, implementations could be switched out (the database could migrate from DB2 to Oracle, for instance or one DAO type could leverage Hibernate, another IBATIS). This pattern had the bogue consequence, though, of logically dividing up a data layer into two types– DAOs and individual domain objects.

think!

For instance, if you had a copasetic Customer domain object, you would also have a CustomerDAO interface type– your Customer object would essentially be a struct and the DAO type would handle CRUD (create, read, update, delete) operations. If you needed to find a particular customer, you’d ask the DAO type, for example, invoking the findCustomer(long id) method on the CustomerDAO object, which would return a fully populated Customer object.

This pattern seemed well and good at the time– I admit to using it extensively on a large project ages ago (after disco though); however, after a while it seemed to be a lot of work– if, because it was my bag, I wanted a Customer object, why did I have to ask the CustomerDAO for it? Why couldn’t I just ask the Customer itself? On top of that, if I wanted to create a new Customer, I had to first populate a Customer object and then pass it to the DAO type and invoke the create method.

I’m sure at the time a lot of smart people eschewed this uptight pattern and designed more natural domain objects; but for me, the tides changed when I read an interesting article about Naked Objects and then looked deeply at Rails (and subsequently, Grails) as they came to mature– these frameworks have no notion of a DAO type– your domain object (Customer) does everything for you– you can create new Customers, save instances, find instance, etc.

I recently found myself building a domain model in Java without the luxury of Grails or GORM; however, I did employ Hibernate and Spring. My initial effort starting going down the traditional DAO-domain object pairing but I quickly found myself disgusted– as a result I started playing around with combining the duo into something as hip (and polished) as what Grails/Rails would give you. My goal, of course, to provide a domain object that handled everything rather than having clients of the domain object have to work with two different trippin’ objects.

In the end, I still have two different objects and an interface type to link them (via Spring); however, clients need only work with one hip type– the domain object. My domain objects support instance methods like create, remove, and update and class methods for find-like methods.

I nonetheless still have a DAO object– it’s essentially a Spring wired HibernateTemplate– this object supports the true CRUD logic and is directly bound to Hibernate. For example, given a Race domain object, the DAO looks like this (minus some instance and class methods, but you’ll get the point):

class RaceDAOImpl implements RaceDAO {
 private SessionFactory sessionFactory;

 public RaceDAOImpl() {
  super();
 }

 public void setSessionFactory(final SessionFactory sessionFactory) {
  this.sessionFactory = sessionFactory;
 }

 public void create(final Race race) {
  final HibernateTemplate tmplte =
     new HibernateTemplate(this.sessionFactory);
  tmplte.save(race);
}

//...

public Race findByName(final String name) {
 final HibernateTemplate hibernateTemplate = new HibernateTemplate(this.sessionFactory);
 return (Race) hibernateTemplate.execute(new HibernateCallback() {
   public Object doInHibernate(Session session) throws HibernateException {
    return session.createQuery(
    "from ... name = ?")
    .setString(0, name.trim())
    .uniqueResult();
   }
  });
 }

//...
}

Note that this class isn’t public– it isn’t intended for outside consumption– the only client to this class (which will be shown shortly) is the domain object (which lives in the same package).

With this DAO object, I extracted an interface type– RaceDAO. This interface is the link between the domain object (Race) and the DAO (that is, the domain object will work with the interface type not the implementation or because it’s everyone’s bag to describe things in terms of coupling– the domain object is loosely coupled to the DAO implementation).

interface RaceDAO {
 Collection<Race> findAll();
 Race findById(long id);
 Race findByName(String name);
 //...other finders...
 void create(Race race);
 void update(Race race);
 void remove(Race race);
}

The domain object (which clients rely on) then relies on Spring (which basically acts as a factory) and composition to expose instance and class methods that indirectly (i.e. delegate via composition) leverage Hibernate to manipulate persistence.

For instance, the Race domain object looks like a normal, hip domain object– it contains various properties (and consequentially getters and setters) related to races (races have runners and results, etc) like so:

public class Race {
 private long id;
 private String name;
 private Date date;
 private double distance;
 private Set<Runner> participants;
 private Set<Result> results;
 private String description;

 //.....more to come
}

The next step could have unfolded in a number of different ways; however, I kept on truckin’ and ended up with something that works– there are certainly pros and cons associated with my choices though (I will point those out shortly).

The DAO interface is linked via Spring in a static block in the domain object like so:

private final static RaceDAO dao;

static {
 ApplicationContext context =
   new ClassPathXmlApplicationContext("spring-config.xml");
 dao = (RaceDAO) context.getBean("race_dao");
}

Note that the type in the domain object is the interface (RaceDAO) not the implementation — Spring is returning some type that is bound to the String race_dao, which in my case is the Hibernate template type shown earlier.

Thus, because the RaceDAO is a static type, I can then expose a series of class methods on the domain object for finding particular race instances like so:

public static Collection<Race> findAll(){
 return dao.findAll();
}

public static Race findById(long id) {
 return dao.findById(id);
}
//...others...

Plus, instance methods on the domain object also delegate to the interface type:

public void create() {
 dao.create(this);
}

Now clients of a particular domain object don’t need to handle or work with various copasetic objects– they work exclusively with a domain object (much like you would in Grails, for instance). For example, the following easyb scenario demonstrates the behavior of a Race instance:

scenario "Race should support finding races by name", {

 when "the find by name method is called", {
  race = Race.findByName("Leesburg Marathon")
 }

 then "the race should have 100 runners", {
  race.participants.size().shouldBe 100
 }
}

As you see in the Groovy code above, the findByName method is a class method– it returns a Race instance, which clients can then work with.

Instance methods on the domain object work too, for example, creating a new race instance and persisting it is as easy as invoking the create method:

scenario "the domain object should faciliate creating new instances", {
 given "a new race is created", {
  new Race("SML 10K", new Date(), 6.2,
     "race the hills of Smith Mountain lake").create()
 }
 then "the domain class should actually find it by name", {
  race = Race.findByName("SML 10K")
  race.description.shouldBe "race the hills of Smith Mountain lake"
 }
}

As I mentioned earlier, there are some bogue disadvantages to this strategy– that is, because it’s its bag, the static block forces clients to load some instance of the DAO– without mocking that instance out, the domain object becomes somewhat heavy. For instance, loading the Race class with a Hibernate wired DAO means that a database must be up and running. Thus, without some mocking of the DAO interface type (and subsequent wiring of Spring) these domain objects can be hard to truly unit test.

The advantage of this strategy is that clients don’t have to deal with a DAO type– they have a more neat-o-natural interface to work with– that being the business object itself (i.e. Customer or Race or Runner, etc). There are still two objects (and a binding type) to work with; however, the DAO is hidden. And in keeping with the spirit of the original DAO pattern, implementers are free to create varying instances of the DAO (should they actually need more than one– unit testing certainly come