Archive for November, 2008

Ranges in Groovy are hip

Groovy, baby!Ranges in Groovy represent a collection of hip sequential values; as such, they facilitate looping in a concise manner. In truth, they function exactly like a for loop; however, they are significantly more terse. For example, the typical for loop in Java looks like this:

for(int x=1; x<=term; x++){
 System.out.println(x);
}

Of course, I could leverage Java’s succinct for loop syntax using the venerable colon (:) if I am able to capture a list of values (i.e. 1 to term) like so:

for(int x : values){
 System.out.println(x);
}

Thus, in both cases, if my term value is, say, 3, the numbers 1, 2, and 3 will be printed. Interestingly, if it’s my bag and I want the exclusive range– that is, I don’t want 3 in my series, I can finagle my first for loop’s second expression to x < term (reminds you of working with normal array’s eh?). The same desired behavior, however, isn’t so easy when it comes to using the newer for loop syntax– I suppose I could remove the last item in the values collection (which presumably is 3, right?).

Groovy has the notion of ranges, which, as mentioned earlier, essentially represent a collection of sequential values. In my case, if term is equal to 3, then I can represent a an inclusive range of 1, 2, 3 as

1..term

and an exclusive range — that is, 1 and 2 only as

1..<term

Ranges facilitate looping rather efficiently. Because they are a list of values, you can leverage the each method call, which is available to any collection in Groovy (remember, objects other than normal Collections can be collections of values — a String is a collection of characters, for instance).

For example, I can achieve the same result as my first copasetic Java example, like so:

(1..term).each{
 println it
}

and if I want to capture the exclusive range (that is, I don’t want term‘s value), I can simply write:

(1..<term).each{
 println it
}

Note how the range effectively lessens the amount of code one has to write to achieve iteration; that is, a range’s sequential-ness enables me to drop having to specify loop conditions (i.e. x < term). And because ranges in Groovy are, in fact, java.util.Lists they can also be leveraged properly in new-style for loop.

If you still find yourself looking for some familiarity with Java and miss the for loop, you can also leverage ranges in Groovy’s for loop using in rather than a colon like so:

for(x in (1..term)){
    println x
}

And don’t forget, you can easily substitute that inclusive range for an exclusive one, baby!

Iteration and looping are an everyday occurrence in development land (just like disco music is an everyday occurrence in la-la land) and on more than one occasion, ranges have materially reduced ceremonial for loops that I would have otherwise had to write. So what are you waiting for? Give them a try, man!

Book review: Beginning Groovy and Grails

I’m a big fan of writing as little code as possible and borrowing everything else. I’m also a big fan of Groovy. I recently had the pleasure of reading Chris Judd, Joseph Nusairat, and James Shingler’s hip “Beginning Groovy and Grails” and in short, I loved it! This book is all about borrowing a slick web framework (and a lot of plug-ins) and leveraging the power and simplicity of Groovy to build web applications quickly.

I used this book extensively to build three different Grails applications and I found that the authors essentially covered everything one would need to it successfully. The first three chapters cover the basics of Groovy nicely, then the book dives head first into Grails with 12 valuable chapters covering GORM, Services, and using various plug-ins. Plus they cover deploying Grails applications, Ajax, and even do some cool stuff with JasperReports. I really liked how they consistently built upon a sample application throughout the entire book– that made comprehending what was going on a bit easier as you, as the reader, didn’t need to re-understand the domain.

In particular, chapters 7 and 8 proved quite helpful as they cover both security and Ajax. I did find myself wishing that the Acegi section went a bit deeper — I ultimately found myself adopting a JCaptcha solution as it proved to be a lot easier; regardless, their in-depth covering of all things related to security broadened my knowledge of the options available in Grails. I ended up using some Ajax components not covered in their Ajax section; however, they do a great job of adding some slick features to an application they build from scratch throughout the book.

I was hoping the Web Services chapter would go a bit deeper as I’m hoping Grails can become a widely adopted option for building RESTful applications; nonetheless, they do a great job of adding the essential CRUD operations to their example application. Plus they tie everything together nicely in the last chapter– 13.

If you are looking to learn Grails quickly, because it’s my bag, I can’t recommend this book enough– it covers designing, building, and deploying a Grails web application and it does so by continually building upon an ongoing application. It doesn’t matter if you don’t have a command of Groovy either, as they do a great job in the beginning and throughout the book of demonstrating Groovy’s essence.

Want better code? Write less of it.

There are various statistics related to the average defect density (i.e. how many defects one can expect to find in a code base); suffice to say, the numbers point to unhip ranges like

20 to 30 bugs for every 1,000 lines of code

and even

100–250 defects per thousand lines of code

Given this amazingly horrible data, what is one to do about it? There are a few possible answers, including:

  • Write a lot of tests
  • Write better code
  • Write less code

The first choice is rather noble; however, it turns out to be a Herculean effort (to say the least) and therefore, few teams actually do it. Writing more hip code is a great idea– there are tons of resources related to writing better code (Robert C. Martin’s “Clean Code: A Handbook of Agile Software Craftsmanship” comes to mind) and I highly recommend teams strive to embrace the craft of coding. In spite of that, I have an alternate suggestion: write fewer lines of code.

If the average application has anywhere from 2 to 25 bugs per 100 lines (oh my goodness that’s an enormous number!) doesn’t make sense to write fewer lines of code? Of course! The question then becomes, how do you write less code? As it turns out, the answer is simple: you borrow code.

Borrowing code is certainly not new, yet I’m continually astonished to find corporations maintaining their own logging frameworks, web frameworks, UI frameworks, the list goes on and on. Why would you write your own logging framework in this day and age? Why not use log4j? Why write a web framework when you can borrow any number of wildly successful ones, such as Rails?

Of course, these frameworks have code in them too– but the beauty is that you end up leveraging the The Wisdom of Crowds; that is, you end up leveraging a community of focused smart people with varying backgrounds maintaining the code and usually a wealth a users providing feedback in multiple environments and situations– making the code more stable.

Aside from borrowing open source libraries to handle commodity issues (i.e. logging, ORM, web frameworks, etc) there are other techniques too. If you write Java code day in and day out, languages like Groovy offer manifold opportunities to lessen your lines of code.

For instance, need to read the contents of a file? If you write this requirement in Java, you could write something like this:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class ReadFile {
 public static void main(String[] args) throws Exception {
  BufferedReader reader = new BufferedReader(
     new FileReader(new File("/Users/aglover/temp/myfile.txt")));
  String output;
  while ((output = reader.readLine()) != null) {
   System.out.println(output);
  }
 }
}

Note, the above Java code isn’t perfect nor am I trying to bash Java! But, it took 12 lines of code to print the contents of a file.

In a language like Groovy, for instance, I can achieve the goal with one line of code.

println new File("/Users/aglover/temp/myfile.txt").getText()

The above code isn’t magic– in fact, it is using essentially the same code from earlier (it’s all Java!). It’s just that someone else wrote it and scores of people are using it and making sure it works day in and day out. Ergo, using 1 line of code means I have 11 fewer lines of code to maintain (smarter people than me are maintaining those other 11 lines, baby!).

If it’s your bag to write better code, man, then I suggest you try writing less of it. Instead, focus on writing the minimal amount of code that serves a business need and borrow everything else. Can you dig it, man?

easyb’s a piece of cake

The tangible disconnect between stakeholders who define requirements and developers who implement them has long plagued software development. In recent years, however, frameworks based on dynamic languages and domain-specific languages (hint– easyb!) are bridging the stakeholder-developer gap by making code read more like normal language. IBM developerWorks‘ tutorial, dubbed “Drive development with easyb” shows how easyb — which provides a more natural DSL that is closely attuned to stakeholders — helps developers and stakeholders collaborate effectively.

In this hip, tutorial, you’ll see first hand, that easyb aims to enable executable yet readable documentation and that you can verify the behavior of anything you write in Java code, in a more natural way. When you are done with the tutorial, you’ll understand the benefits of collaborative stories implemented with easyb and how this framework makes collaboration easy.

So what are you waiting for, man? Go read it!

Poll: Java’s 2008 memorable moment

Napoleon Bonaparte cleverly mused long ago that

history is the version of past events that people have decided to agree upon.

Indeed, as 2008 begins to draw to a close, it’s time to start reflecting on the hip world of Java, and how over the course of this year, it may have changed for better or for worse. Because it’s my bag, a few events, occurrences, or aspects that come to mind (in no particular order, man) are

  • September’s inaugural JVM Language Summit, which brought together the various language factions in an effort to ultimately learn from one another and incorporate new features in the underlying execution engine for all languages. In essence, this summit was tangible realization that Java is now more of a platform than a language.
  • The release of Google’s App Engine, which includes an application environment that notably doesn’t include Java. What’s particularly interesting is a subsequent move by Sun to more formally embrace Python.
  • A general awakening to the applicability of REST. REST is by no means a new buzz word; however, this year saw JSR 311 formalize and the Restlet framework’s 1.1 release (after almost a year since its 1.0 debut). What’s more, REST articles appear to be increasing as well as related conference topics.
  • Java EE 6, which had some pundits declaring “Java EE 6 gets it right“, while leaving others to deliver a collective yawn over the news.

What’s your version of 2008′s most memorable moment for the world of Java? If it’s not listed below, leave a comment and leave your record of Java’s history, baby!

Java's 2008 most memorable moment
View Results