Archive

Author Archive

[].inject(“Groovy”){}

January 25, 2009 Peabody 5 comments

The collection helper methods like each, findAll, and collect are among the clearest productivity advantages of Groovy over Java. For reference, here’s a list of the common collection helper methods on the Groovy Quick Start page (after opening the link you’ll have to scroll down to them).

The inject method is among the most interesting of them all but is not utilized often by Groovy developers. It’s useful but somewhat difficult to understand, relative to the complexity of the other collection helper methods, so many developers get the job done without inject and never bother to learn about it. I encourage everyone to learn inject so that they can understand another approach for attacking their problems and choose the most appropriate approach. The inject method is also a great first step in learning a little about functional programming.

Functional Style – A stork story for inject
The Scala and Clojure languages on the JVM have aroused interest in functional style programming. Even with an imperative language like Java we can alter our programming style to more of a functional one, so learning the functional tenets can be very valuable to your arsenal.

Let’s take some Groovy code that calculates the sum of numbers 1 through 10.
def total = 0
(1..10).each{total += it}
return total

Here we apply a closure to each value in the 1..10 range. But as we repeatly apply this closure we also need to keep track of a total variable, which changes with each iteration.

In pure functional programming variables are… not allowed. This poses an interesting twist to our problem. How can we accomplish the same functionality as the above code without any variables?

The answer to most “How can I solve this without variables?” questions: Recursion.

Let’s examine how we totaled up values 1 to 10:
(((((((((((0)+1)+2)+3)+4)+5)+6)+7)+8)+9)+10)
Each set of paranthesis describes the value of total at some given point in time starting with 0 and expanding out to its final result of 55. Consequently, total gets set to 11 different values over its lifetime and only the last of those 11 was actually what we wanted.

The other danger here is that another developer might “refactor” your code by moving all variable declarations to the top of methods. I’ve inherited Java code like this quite often, where the beginning of some ginormous method sets a bunch of values like total = 0, even though taking the initializing value out of context actually makes the code more confusing.

With inject we can make the value of total clearer by keeping the calculation within the scope of its declaration. We “inject” the initial value of 0 and at each iteration the previousResult value represents what used to be represented by a waffling total variable.
def total = (1..10).inject(0){previousResult, iterationValue ->
  previousResult + iterationValue
}

The concept of inject in Groovy is identical to that of a left fold in functional programming. Ironically, the Groovy’s implementation of inject does not use recursion for, what I’m assuming, are performance reasons.

sum()
We’ve been using a very simple example. Those familiar with Groovy might ask why not just use the sum() method available to lists:
(1..10).sum()

Well, I’m glad you brought it up because there’s more to sum() than you may have realized.

You see, sum() allows you to “inject” an initial value.
(1..10).sum() // 55
(1..10).sum(0) // 55
(1..10).sum(3) // 58

This doesn’t seem incredibly valuable at the surface, but let’s look at why it can be.

Try calling sum() on an empty list:
[].sum() // null

Yes, the result is null. Most folks would assume that the result should be 0. So why isn’t the result 0? You have to realize that the sum() method merely requires that the objects in the list have a plus() method, which means that Groovy’s sum() method can’t assume that the empty list you passed in held Integer values.

For example, you could join strings in a list using sum():
["strings ","in ","a ", "list "].sum() // "strings in a list"

If you had an empty list intended for Strings, a sum() of 0 doesn’t make sense – an empty String would be more appropriate, so use sum(""). If you don’t “initialize” a value into sum() you could end up with null if your list is empty and that could break some assumptions in your code, leading to a NPE. It’s often a good idea to “initialize” the sum() method with a value, much like you would do with inject().

inject() to build collections
Java programmers switching to Groovy often use each{} for everything involving iterations. They write the equivalent of an imperative Java for loop:
def oneToTen = (1..10)
def doubles = []
oneToTen.each{myValue->
  doubles.add(myValue*2);
}
return doubles

They’re often thrilled to find out that using a different collection helper method makes their code more readable and concise:
def doubles = (1..10).collect{ it*2 }

Always scan your Groovy code for a collection helper method code smell:
If your each{} or other collection helper method (findAll, collect, etc.) has a variable declaration in the line before it, you’re likely to benefit by using a different method.

I usually play around in the GroovyConsole (just type groovyConsole in your command line if you have Groovy installed) to decide which collection helper method does the job best. It’s a fun challenge to include inject into the mix even though it has only emerged once as the victor in my production code… and honestly I can’t remember what that was and I don’t have access to the code any more. Bummers.

There’s an inject example at the bottom of a post we made on chaining and currying closures back in November ‘08. Chris made a clever improvement in the comments section of that post as well. Thanks for that, Chris! We greatly welcome any improvements or questions here and we hope to see even more in the future from our readers.

Categories: Groovy Tags: , , ,

Liferay Portal is pretty snazzy

January 13, 2009 Peabody Leave a comment

I’m a big fan of technologies I can play with quickly, without having to journey to Mordor or wave dead chickens over glyphs in the sand. Basically, I hate setting up environments. I had this running quickly. Yay for me.

I’m sitting in the evening COJUG (Central Ohio Java User Group) session given by Ayan Dave of Quick Solutions on the Liferay Portal product. I almost didn’t come. Virtually every developer I know that’s worked on a portal project hated it. I think some of them even had the project scrapped.

I hear “portal” and I want to run the other way.

But I’m being brave tonight. Luckily, it was free and very simple to get started with Liferay Portal. It comes prepackaged with one of many choices of servers. I chose Tomcat.

I started up the instance of Tomcat and opened my browser to http://localhost:8080/

A login screen. I created my own account but didn’t seem to have permissions to do anything… went back to the getting started guide (link above) to find I could log in as test@liferay.com with a password of test… that seemed to give me admin privileges.

In no time I could drag and drop the couple of default widgets. That was kinda gratifying.

At the top-right is a dropdown menu. Select Add Application. You’ll get a nice selection of already developed portlets. I chose Finance > Stocks. Played around with it. Pretty stinking cool.

Try it out yourself. Have fun!

Thanks to Ayan for presenting at COJUG tonight.

PS – I also had cake tonight. The cake is not a lie!

Categories: Uncategorized

Ajax Experts Unite!

January 12, 2009 Peabody Leave a comment

There will be a Sun Certified Ajax Developer exam coming out soon.

They need help deciding what weightage to give various topics, so a bunch of experts are needed to give their opinions in a survey-bobber-thingy.

I am not an Ajax expert, so I will not be taking the survey. However, if you happen to be an Ajax expert, please take a couple minutes to take the survey.
http://certification.sun.com/sesCert/

Thanks!

Categories: Uncategorized Tags: ,

poking Unit with a stick (Scala)

December 22, 2008 Peabody 3 comments

Scala has a thingy called Unit. For those coming from Java, Unit is similar to void but it is an actual type.

By my understanding, there’s only one actual instance of Unit ever and its value is ().

If you go to the Scala interpreter (type scala in a command prompt if you’ve downloaded Scala) you can assign Unit to a variable… er, um value in a few different ways.

One way is to simply create a value and assign () to it:
scala> val x = ()
x: Unit = ()

Another way is to make a value typed as Unit. You’re allowed to assign anything to it because pretty much any object in Scala can be automatically converted into Unit:
scala> val y: Unit = “turn me into Unit”
y: Unit = ()

I suppose the automatic conversion is because Scala methods return the value of the last expression. If Scala didn’t do this trick, we’d have to end every Unit-returning method with a gratuitous ().

Yet another way to end up with a Unit is to create a method without an assignment:
scala> def z(){“turn me into Unit too”}
z: Unit = ()

What’s this I say about a method without an assignment? Well the method z() I wrote above looks like a normal method to many folks (especially Groovy people). However, in Scala, most methods are created with an equals.
scala> def a() = “hello”
a: ()java.lang.String

Skipping the = is like automatically typing the method return as Unit, as if the z() method above were written as:
scala> def z(): Unit = {“turn me into Unit again”}
z: ()Unit

One weird thing I found with Unit is if I try to call getClass() on it:
scala> ().getClass
res1: java.lang.Class[_] = class scala.Predef$$anon$1

So it appears (), or Unit, is an anonymous inner class of something called object Predef.

Predef is a neato object. It pretty much is a way to get what appears to be a bunch of keywords and methods built into the Scala language, like println() and assertions.

Looking through the Predef source code, after being quite tickled by the ASCII art in the Scaladoc, I found the answer to another question I had about Unit – I had seen once in the Artima book unit with the lower case ‘u’. I originally thought it was a typo but tried it out in code and it seemed interchangeable. Line 36 of Predef, though the line is deprecated explains where unit (lower case ‘u’) comes from.

This was my experience digging into Unit in Scala. Try it out yourself and see what you can discover. Maybe you can uncover why ().getClass returns that weird Predef$$anon$1 thing.

Categories: Scala

How to use Groovy without management finding out

November 20, 2008 Peabody 5 comments

I hang out with Ruby guys and gals when I can. These folks are such a blessing to my brain. If you don’t have Ruby friends, find some. Google for “yourcity ruby brigade” to find a Ruby user group in your area.

I’ve often heard Ruby friends talk about utilities they wrote in Ruby that essentially generate boilerplate Java code, and I used to shudder at the thought.

I always figured “You have a great language that can do so many yummy things, why are you using it to write icky code!?”

I think I’m beginning to understand now: The icky language (sorry for the blasphemy, but yes, I mean Java) runs faster. It’s also more likely to be accepted by the governors in your projects. If you don’t know what I mean by governors, they’re the poor folks that take the heat and lose bonuses when stupid geeky experiments with unproven technologies ruin a project. These folks love the status quo. And bonuses. Your geeky technologies pose a threat to both.

Groovy noobs and doubters ask “How can I get management to approve using Groovy in my project?” Well, you can write Groovy scripts that no one needs to know about. Write scripts that generate Java code.

I’m not completely off my rocker.

Grails does some cool code generation to write Groovy views and controllers based on your tiny li’l POGO domain classes. It’s so awesome not to have to write boilerplate code or have to start everything from scratch. I can literally create an entire CRUD webapp in a couple minutes, even with a couple beers in me (which, for the record, only happens at home on my own time – I swear). Why code generation is awesome: Doing tedious code manually from scratch is like a coding limbo… never really touching heaven or hell but it passes the time.

Code generation good. Hulk like code generation. Tedious code make Hulk angry! Hulk smash!!!!!

Just to play around and set my first goal low, I challenged myself to write a Groovy script that creates a Java constructor. All my favorite IDEs do this for me already, but I’m not going to let practicality get in the way of fun… certainly not when I’m coding on my own time at home! Time to play!!!

class Person{
  private String firstName;
  private String lastName;
  private int age;
}

void constructor(Class clazz){
  def props = clazz.properties.declaredFields.findAll{
    // filter out the properties I do not want
    !it.toString().contains("static") &&
    !it.toString().contains("metaClass")
  }.collect{
    // I want the property type and name
    [it.type.toString().split()[-1].replaceAll('java.lang.',''), it.name]
  }
  // dump out the constructor!!! yay!!!
  print " public ${clazz.name}("
  print props.collect{"${it[0]} ${it[1]}"}.join(', ')
  println "){"
  props.each{ println " this.${it[1]} = ${it[1]};"}
  println " }"
}

 

constructor(Person)

All I have to do is paste in a new class definition like I did with the Person class and call my dandy new constructor() method, passing to it the name of my class. In Groovy I don’t have to say Person.getClass() or even Person.class – just plain ol’ Person is good enough.

My console dumps out:
  public Person(String firstName, String lastName, int age){
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

Not too shabby.

Keep in mind the DRY principle. Your first priority is to write Java code without any duplication. In most cases you can avoid duplication by simply following basic OO principles.

If, however, boilerplate code seems like a necessity, consider generating it.

Chain those Crazy Groovy Closures with Currying, Case Study: Mimicking Intercepting Filter

November 3, 2008 Peabody 7 comments
Below is a post I wrote a little while back but never published. If you’re wanting to learn better how closures work or how to use currying, this can be a really fun exercise. I didn’t publish this earlier because I didn’t want to encourage anyone to implement this in production code as if this were some kind of pattern.
 
Please, treat this post merely as something fun to play with. Do not use this in production code. Please, I beg you. Think of the kittens.
- Peabody
———————————————
A week ago Josh and I wanted to chain a bunch of behaviors together in Groovy.
 
One of the first possible solutions that popped to mind was the very flexible Intercepting Filter pattern common to Java EE web applications.
 
I think we ended up deciding, for what we actually needed, this neato solution wasn’t the best fit. But the process was extremely rewarding and sharing it might help some folks get a better feel for how powerful closures can be and get a little more familiar with currying.
 
Here’s the basic pattern diagram for the Intercepting Filter from Sun’s site. The important parts here are the Filters One, Two, and Three. We want to be able to call a chain of these filters and each filter will be responsible for doing any pre or post processing and likely call the next filter in the chain at some point in the middle.
 
Figure 7.1
Here are our three filters. They’re simply closures that accept another closure as an argument. In JavaEE, the Intercepting Filter gets added to a chain of other filters. Each one can run some pre-processing logic, call the next item in the chain, then call some post-processing logic before returning. In our closures, the pre and post processing both simply output something to the console and, in between those, we call the next item in line with c.call(). The c={} argument defaults our c variable to an empty closure if no other closure is passed in as an argument. 

def one = { c={}->
  println "one*";    c.call();  println "*one"
}
def two = { c={}->
  println "two*";    c.call();  println "*two"
}
def three = { c={}->
  println "three*";  c.call();  println "*three"
}

Note to Reader: Please copy this code into your GroovyConsole as you follow along. It will be much, much more fun for you that way. ;)
 
So now I can call one of my fancy new closures like I would a method.
Try this:
two()
Output:
two*
*two
 
I called the two closure with no parameters. This worked even though the signature for two has an expected variable of c. It did not complain because I declared it c={} which means that it will just default to an empty closure if I don’t supply one.
 
Let’s call our two closure again now but supply it with another closure as an argument.
Try this:
two{ println ‘hey there!’ }
Output:
two*
hey there!
*two
 
That worked pretty well. Now let’s try combining the closures.
Try this:
one{two{three()}}
Output:
one*
two*
three*
*three
*two
*one
 
That’s pretty sweet. But we might end up needing a handful of behaviors to run through and that curly brace syntax can become messy quickly.
 
We know that with a little currying we can build all of my little closures into a bigger closure.
def myChain = one.curry(two.curry(three.curry({})))
Then we can call that one chain by itself.
myChain()
 
But we want to dynamically build that chain. We should be able to call it like:
chain([one, two, three])
Or if we had more closures:
chain([one,two,three,fo,get,yo,wo,man,on,tha,flo])
 
That allows us to pack a lot of behavior into a small amount of code and we can mix, match, and put these behaviors in any order we want.
 
Here’s a little method to help us with that.
def chain(List commands){
  def chainToCall = {}
  commands.reverse().each{command->
    chainToCall = command.curry(chainToCall)
  }
  chainToCall()
}
 
Give it a try! :)
 
PS – Here is an even shorter version of that chain method by using inject. One of my next posts to Inside the Machine will explain inject in greater detail. I hope you can see that inject allows much more succinct code.
def chain(List commands){
  commands.reverse().inject({}){chainToCall, command->
    command.curry(chainToCall)
  }()
}
Categories: Groovy Tags: , ,

A quirk in Groovy maps and GString coercion

October 22, 2008 Peabody 1 comment

I slipped into my old Java ways recently and lost a bit of Groovy magic in the process. I was calling the get method on a map and getting null back, though I was quite confident I should have gotten a value from the map.

Let’s start with a simple map in Groovy:

def map = [a:'x',b:'y',c:'z']

 

Now we can print out the value for key ‘a’ with magical Groovy syntax:

println map['a']  // this outputs x

 

Or we can slip back into our old Java ways and it will still works.

println map.get(‘a’) // this also outputs x

 

But what if we want to look up a value using a GString with an inner variable instead of the normal String?

def aVar = ‘a’

println map["$aVar"] // still good, this outputs x

println map.get(“$aVar”) // oh snap! this outputs null!

 

As you can see, using the Java style of .get() using a GString that contains a variable doesn’t work.

 

But… wait a second! Aren’t ‘a’ and “$aVar” supposed to be the same thing in Groovy!?

println ‘a’ == “$aVar” // true

 

Not entirely. Yes, you learned that == in Groovy is the same as calling .equals in Java. But check this out!

println ‘a’.equals(“$aVar”) // double snap!! it’s false!!

 

So == obviously isn’t exactly the same as .equals – if you check out the Groovy Operator Overloading page, you’ll see a little sidenote:

** Note: The == operator doesn’t always exactly match the .equals() method. You can think of them as equivalent in most situations. In situations where two objects might be thought “equal” via normal Groovy “coercion” mechanisms, the == operator will report them as equal; the .equals() method will not do so if doing so would break the normal rules Java has around the equals method. Expect further improvements to Groovy over time to provide clearer, more powerful and more consistent behavior in this area.

 

In case you’ve read that sidenote before but you didn’t know what it meant by “coercion” mechanisms, now you know.

Keep all this in mind next time you’re dealing with a map in Groovy. Stick to using the Groovy array-ish square brackets instead of using the traditional .get() and you’ll avoid a potential headache.

Categories: Groovy Tags:

Spring AOP autowiring scares the poopoo out of me

September 29, 2008 Peabody 1 comment

Usually brains are quick to sort everything into one of two categories: GOOD and BAD

Some things refuse to go to either category or, even worse, ping pong back and forth until who knows what else gets scrambled up there. My brain still struggles with categorizing the following…

 The Scala Language

 Candy Corn

Richard Simmons Richard Simmons

Until now, autowiring in Spring was somewhere between Candy Corn and Richard Simmons. Let me explain how it got there.

Every ounce of logic in me had been screaming that autowiring is a good thing because it takes away a bad thing: XML. Autowiring should cannonball at light speed into the GOOD half of my brain pool, splashing memories of Oregon Trail out my nose.

But the brain isn’t very logical. It’s mostly associations. We often get hunches, gut feelings, and red flags but we can’t always articulate or why. 

Saturday morning (you’d think I’d have better things to do) I finally realized why it’s so hard to let go of XML, this melted green icing of our framework cake. When I inherit a project here’s what I do get my bearings, since there’s absolutely no documentation available because some ivory tower Architecture committee banned wikis for “security reasons” yet our division was too cheap to get SharePoint and too disorganized to keep a few Word docs on a shared drive (yes this is from past experience):

1) Read the JavaDoc. There are only two types of information here: author names (I commit these to memory so I can retrieve formal apologies – it’s a small world and I will meet these people some day) and some banal rewording of class and method names (a comment for a class called DataHelper will say “A class to help the data”) 

2) Look at unit tests. Methods like testSetDescriptionOnDataHelper reveal that the agile developers before me were apparently only concerned that Eclipse didn’t screw up auto-generating their getters and setters.

3) Poke around classes, trying to at least figure out which ones are domains. Cross my fingers that design pattern names like DAO and BusinessDelegate are mashed into the class names just to help my brain spatially map the architecture.  

4) Grumble about the naive programmer who thought “program to the interface” meant that we should create an army of interfaces to Impl-cripple our architecture.

At this point, my brain begins throbbing under pressure and blood shoots out of my ears.

4) Give up looking at code.

5) Read the configuration XML file. This is the only hope I have of learning anything about the application.

I love the XML I hate. It forces bad developers (and sometimes brilliant developers under ridiculous timelines) to do something kinda good.

What scares the poopoo out of me about autowiring is… what in the world I’m going to do at step 5 when my monolithic XML is gone!?

Categories: Uncategorized Tags: , ,