July 2008

easyb is hip enough for JET

kiwiThe copasetic virtues of easyb have made there way to New Zealand and will be discussed during the Java Emerging Technologies Conference 2008 in Auckland on September 17th. My friend and über Java technologist, John Ferguson Smart will be chewing the fat over easyb and as he states:

The talk will be very practical…There will also be some live demos just to prove that it really is as easy as it looks!

Needless to say, man, having John, who also happens to have authored the veritable bible of all things related to high speed Java development (also known as Oreilly’s Java Power Tools), talk about easyb is great news! In fact, if you didn’t already see it, John also blogged about easyb in which he aptly pointed out that BDD enables you to think

about what your class “should” do– in other words, you are thinking specifications. The difference is subtle, but this turns out to be a much more intuitive way of driving development than thinking in terms of raw tests. Rather than saying “what do I test”, you are saying “what should my class actually do”, or “how should my class behave”. Which is very much the spirit behind TDD.

Well said, baby! If you are hip enough to be located anywhere near New Zealand, you should definitely plan on attending JET and while you are at it, join the party baby and check out easyb.

Smokin’ the decorator pattern with Groovy

decorator
I recently found myself needing to add additional hip behavior to an object that handled feed parsing– i.e. I needed to add a series of filters (such as location and price) to the items being obtained from the feed. Of course, the easiest (and probably the most naive) way to achieve such a goal is to have added a few conditionals to the feed parsing object itself; however, I realized that this particular problem already had an answer to it– the decorator pattern.

A copasetic example of the decorator pattern in use is Java’s IO library– for example, in the Java code below, a FileReader instance is decorated by a BufferedReader instance.

BufferedReader br = new BufferedReader(new FileReader("readme.txt"));

As my friend, David Geary, wrote many years ago, decorating objects, such as with a BufferedReader, essentially forwards

method calls to the objects they decorate…Decorators add functionality either before or after forwarding to the object they decorate..

So in the code above, decorating the FileReader instance with a BufferedReader facilitates “buffering characters so as to provide for the efficient reading of characters” while reading a file.

One key aspect of the decorator pattern, baby, is a reliance on polymorphism; consequently, in normal Java, for example, the decorator object must implement the same interface (or extend some base class) as the object it intends to decorate; consequently,

the Decorator is indistinguishable from the [hip] object that it contains. That is, a Decorator is a concrete instance of the abstract class, and thus is indistinguishable from any other concrete instance, including other decorators. This can be used to great advantage, as you can recursively nest decorators without any other objects being able to tell the difference, allowing a near infinite amount of customization.

Indeed, the indistinguishable nature of objects facilitated via polymorphism is fundamental to a cornucopia of patterns. And with Groovy, polymorphic behavior can be achieved more easily; that is, patterns that rely on polymorphism can be realized without class hierarchies.

For instance, the original object that required additional behavior is a normal class defined in Groovy:

class FeedReader {

 def readFeed(interestItem, feed, lastUpdateTime) {
  def input = new SyndFeedInput()
  def mefeed = input.build(new XmlReader(feed.toURL()))
  def lstdate = mefeed.entries[0].publishedDate as Date

  def feeditems = []

  if (lstdate.after(lastUpdateTime)) {
    mefeed.entries.each { entry ->
     if (entry.publishedDate.after(lastUpdateTime)) {
      feeditems << new FeedItem(item: interestItem,
        title: entry.title, link: entry.link,
        description: entry.description.value,
        publishedDate: entry.publishedDate)
      }
    }
   }
  return feeditems
 }
}

This class defines one method, readFeed, that reads an RSS/Atom feed using ROME and every item added since the last time the feed was parsed is added to a collection and consequently returned to the caller. As I noted earlier, one could simply add another set of conditionals to the closure to check for, say, the price and location of an item before adding it to the collection; however, a more extensible solution is to apply the decorator pattern and thus decorate the FeedReader.

For instance, in the case of filtering on the price of an item (which, by the way, is dynamically determined based upon the entry’s title), all I had to do was to create a new trippin’ class, in Groovy, that merely contains a method with the same signature:

class PriceFilter {
 private def feedReader
 private int maxPrice

 public PriceFilter(feedRdr, price) {
   this.feedReader = feedRdr
   this.maxPrice = price
 }

 def readFeed(interestItem, feed, lastUpdateTime) {
   def items = this.feedReader.readFeed(interestItem, feed, lastUpdateTime)
   def filteredItems = []
   items.each {item ->
    int iprice = item.getPrice().toInteger()
     if (iprice <= this.maxPrice) {
      filteredItems << item
     }
    }
  return filteredItems
 }
}

Note how the PriceFilter class also has a readFeed method and that that method first defers to an instance, such as FeedReader, and then decorates the result– that is, the PriceFilter class checks each object returned and compares prices. Note too, that I’ve defined a constructor that takes an instance of some object that ideally has a readFeed method– this object isn’t tied to a FeedReader or an interface– it is only tied via the method contract.

Groovy purists will probably bark at me for defining a constructor– indeed, had I dropped the private moniker on the class’s instance variables, a constructor would have been generated for me. In this case, because it’s my bag, old habits never die and I purposely made those instance variables private and thus am forcing clients to properly initialize the object for proper usage.

As you can see, Groovy’s dynamic typing permits me to arbitrarily decorate objects– all that I need to do is ensure decorators have the same method. Then by leveraging constructors, one can easily chain instances like so:

def priceFilter = new PriceFilter(new LocationFilter(mock, locs), 20)

In the code aboe, two filters are applied to the original FeedReader, which, in this case, is actually a mock object that simply has a readFeed method! By the way, this sort of sans-interface polymorphism isn’t limited to Groovy only– the original FeedReader class could have easily been defined in normal Java. Plus, this sort of voodoo polymorphicness can be easily achieved in Ruby, JRuby, Python, and Jython to name a few.

Groovy definitely makes it easier to implement fundamental design patterns by enabling you to leave out the standard scaffolding; what’s more, ubiquitous polymorphism via signatures rather than hierarchies makes testing a whole lot easier! Think about it for a second– my FeedReader instance requires a feed to parse! But I can almost effortlessly mock it by creating an object that responds to a readFeed method. That’s it! Is that smokin’ or what, baby?

The weekly bag– July 25

Enjoy the hip links, baby:

RESTful services without the sweat

Representational state transfer (also known as REST, baby) is an approach to designing loosely coupled applications that rely on named resources rather than messages. As it turns out, the most involved part of building a RESTful application is deciding on the resources you want to expose. Once you’ve done that, building RESTful Web services a snap, especially if you use the Restlet framework, which greatly simplifies the task of defining and implementing RESTful services.

Check out IBM developerWorks‘ tutorial dubbed “Build a RESTful Web service“– in it, you’ll get to know what REST is and how to build RESTful applications with Restlets, plus, you’ll see how to deploy and test them while you are at it!

The weekly bag– July 18

Enjoy the reading, baby:

Reality checking the tools market

ahhh!
Albert Einstein once mused:

“Reality is merely an illusion, albeit a very persistent one.”

Unfortunately for the vast majority of commercial players in the Java tools market, he may be incorrect– reality isn’t an illusion. It’s a harsh (and rather persistent) truth. You need only scan the various development tools you use on a daily basis to see that free, for the most part, is king these days.

Two recent SDTimes articles do a great job of highlighting this reality: first, Andrew Binstock wrote an article dubbed “Java tool market disintegrating” in which he states that the market for selling tools to Java developers

has been unhealthy for years. It is hard to think of a single Java-only tools company that has grown and prospered. One exception is KLGroup, which later became Sitraka and sold for a small fortune to Quest Software during the Internet bubble. Beyond it, though, things drop off quickly. Small companies struggle, living out their bets on Java.

He goes on to highlight three recent events such as Agitar’s demise, Enerjy’s freebee spree and lastly, CodeGear’s mercy acquisition (one can argue Embarcadero received an 85% discount on the purported $150 million value of CodeGear). Each of the aforementioned affairs do suggest the market for selling tools to Java developers (keep in mind that the CodeGear acquisition included non-Java tools and the support revenue associated with them i.e. Delphi) is rather limited.

Second, SDTimes was quick to release the news that McCabe Software is acquiring Agitar’s assets. On the surface, that could be good news, except for the fact that a Gartner analyst is purported to have said that Agitar’s product

might be a good fit within larger suite or a family of QA technologies.

Because it’s my bag, using the word might in the same story regarding an acquisition is not exactly positive. It’s like having the word disappointing show up on your resume or during a reference check, man. What’s more, no dollar figure was highlighted in the article nor the official press release, suggesting Agitar’s IP was picked up for peanuts (do you think McCabe received an 85% discount like Embarcadero? $5 million? It’s hard to believe they would pay even that much).

It remains to be seen if McCabe can attain a reasonable market share with the purchased assets; suffice to say, history (and don’t forget reality, baby!) are working against them.

That’s not to say that all commercial tools are doomed– in fact, you need only go to a Java oriented conference to see that IntelliJ continues to impress legions of smart people, who do pay for the copasetic tool even in the face of free competition from the likes of Eclipse. Plus, Atlassian continues to wow developers across the globe (they sell various products, however, like JIRA, which isn’t necessarily a tool marketed to and used by Java developers alone).

It seems a more apt mechanism for describing reality for the majority of commercial tool players in the Java market is, as Jane Wagner eloquently stated,

“Reality is the leading cause of stress amongst those in touch with it.”

Indeed, as Andrew Binstock pointed out in his article and as Atlassian is currently demonstrating, the actuality of the Java tools market is that those companies that wish to prosper selling tools to developers must offer a cornucopia of products to a wide range of audiences. That is, they must sell tools not only to developers but to other stakeholders in the application life cycle– and even then, success (i.e. healthy revenues) is no guarantee. Plus, in this Age of Aquarius, it helps if the company is bootstrapped and thus isn’t required to provide exponential returns in a short timeframe. Can you dig it?

RESTing at ease with JSR 311

REST is a style of designing loosely coupled Web applications that rely on named resources rather than messages. Ingeniously, REST piggybacks on the already validated (and successful, don’t you think, man?) infrastructure of the Web– HTTP. That is, REST leverages aspects of the HTTP protocol such as GET and POST requests. Because it’s REST’s bag, RESTful applications turn out to be quite clean in their API as you don’t spend a lot of time reinventing the wheel– you get a lot for free when leveraging HTTP.

I’ve been keeping my eye on JSR 311 as it seemed to make a lot of sense to leverage attributes given the template-like pattern employed by the Restlet framework. For instance, without attributes (and by correlation, JSR 311, which is supported by a developmental version of the Restlet framework), you are forced to override specific methods in the base framework’s hip Resource class associated with HTTP verbs– public void post(Representation representation) handles HTTP POSTs; what’s more, given that the framework doesn’t actually know if a subclass has implemented a particular method, you must also override the allowPost method in the case of POST.

In fact, leveraging attributes in the case of JSR 311 (or, as previously mentioned, the 1.1 snapshot version of the Restlet framework) is a lot like comparing JUnit 3.8.1 to JUnit 4– the entire framework paradigm is shifted, which has the result of a lot less noise (a.k.a code).

For instance, implementing a GET request via JSR 311 is as easy as leveraging the GET attribute:

@GET
@ProduceMime("text/xml")
public String get() {
 Collection<Race> races = Race.findAll();
 return this.reporter.racesToXml(races);
}

Note, this code is leveraging Jersey, Sun’s reference implementation of JSR 311 (which recently released version 0.8). What’s more, JSR 311 specifies mime annotations for both requests and responses — for instance, the get method above responds with a mime type of “text/xml” — you can easily specify JSON, etc too.

Handling other requests, such as a POST request is just as easy– just use the corresponding copasetic annotation (for instance @POST). Note too, with mime types, you can specify accepted request types. In the case below, the post method will only accept “text/xml”.

@POST
@ConsumeMime("text/xml")
public Response post(String xml) throws Exception {
 long id = this.consumer.createRace(xml);
 return Response.created(uriInfo.getBaseUriBuilder().
    path(Long.toString(id)).build()).build();
}

Of course, the two method above are related to a particular path or URI– JSR 311 supports the @Path annotation, which interestingly enough, is inheritable such that a method can expand upon a base path specified at the class level. For instance, the method above live in class defined as follows:

@Path("/race")
public class RacesResource {
  //...
}

Thus, all exposed RESTful methods will respond to the /race URI (i.e. a HTTP GET to /race will be handled by the get method and a HTTP POST to the /race URI will be handled by the post method (provided the request be of mime type “text/xml”, don’t forget!)). Methods can expand upon the /race URI by providing their own @Path annotation, which will effectively append the specified URI to the base URI.

There are certainly more than a few ways to skin the REST cat in Java, baby– you’ve got, to name a few, Restlets, Grails, 1060 NetKernel, and now JSR 311 via Sun’s Jersey. Each framework comes with its own bells and whistles; nevertheless, JSR 311 and Jersey definitely lower the barrier for building (and deploying) RESTful applications even if they are fairly late to the party.

It’s ok to wet yourself every once in awhile

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?

easyb 0.9 hits the streets

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.