Who needs a mock framework?

July 26, 2009 12 comments

In Groovy, you can create mocks & stubs using native language features, so you can forget about learning a mock framework.

class Author {
  def getName() {
    return 'Josh Brown'
  }
  def isFamous() {
    return false
  }
}

Let’s stub the isFamous method:

def author = [isFamous: {true}] as Author
assert 'Josh Brown' == author.getName()
assert author.isFamous()

(If you haven’t already, stick the above code in your groovyConsole, run it, and play around with it.)

When mocking and stubbing are so easy to do with the language itself, using a mock framework is overkill.

[Update: Bob Martin recently wrote an excellent post about Manual Mocking.]

Tags: , ,

Story time with easyb

January 27, 2009 2 comments

Everyone loves a good story.
 

Star Wars Trilogy

 

With easyb, you can write stories in your code!

scenario "the Death Star destroys Alderaan", {
    given "the Death Star", {}
    and "Alderaan", {}
    and "Alderaan is targeted by the Death Star", {}
    when "the Death Star fires", {}
    then "Alderaan is destroyed", {}
 }

You probably could’ve written that with the stakeholders yelling over shoulder. No – the Death Star should destroy Yavin IV, not Alderaan!!! If you’re writing readable code in front of them, you might be able to get them to make a decision while you’re at your keyboard.

Now you have executable documentation, and the stakeholders can leave the party. And once they’re gone, you can move on to writing some Groovy code to fill in those empty squiggly braces:

scenario "the Death Star destroys Alderaan", {
    given "the Death Star", {
        deathStar = new DeathStar()
    }
    and "Alderaan", {
        alderaan = new Planet(name:"Alderaan")
        Galaxy.planets << alderaan
    }
    and "Alderaan is targeted by the Death Star", {
        deathStar.target = alderaan
    }
    when "the Death Star fires", {
        deathStar.fire()
    }
    then "Alderaan is destroyed", {
        Galaxy.planets.shouldNotHave alderaan
    }
}

Now run it and watch it fail. Ah, the joy of xDD…

From here, you can write the DeathStar, Planet, and Galaxy classes you need to make it pass. Run it again! Refactor! Repeat!

Now you have documentation that’s readable, executable, and verifies that your code does what it’s supposed to do! Wasn’t that easy?

Tags: , , ,

[].inject(“Groovy”){}

January 25, 2009 7 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.

Liferay Portal is pretty snazzy

January 13, 2009 2 comments

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!

Ajax Experts Unite!

January 12, 2009 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!

poking Unit with a stick (Scala)

December 22, 2008 5 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.

Unsolicited LinkedIn Recommendations

December 11, 2008 2 comments

Inspired by Gayle’s post, I wrote an unsolicited LinkedIn recommendation a few days ago. I found one of my previous managers on LinkedIn and just decided to recommend him. He was a great manager/architect/tech lead, so he deserved it. I wasn’t looking to get anything from it – I just thought he’d appreciate it, and I was hoping to make his day (or at least his evening, or hour, or something). I’m not sure how he reacted.

A friend and I were discussing this, and he told me he wouldn’t want an unsolicited recommendation.  I never asked why – maybe he thought I would expect some sort of payback.  Hopefully he’ll speak up in the comments.  ;)

I, on the other hand, would love to get an unsolicited recommendation on LinkedIn.  I’d be really excited about it (especially since LinkedIn keeps showing me that my profile is only 80% complete).  And I think it would motivate me to pay it forward by recommending someone else.  And pretty soon, everyone would have a recommendation…

So how would you react if someone gave you an unexpected recommendation on LinkedIn? Would you be thankful, excited, appreciative? Or would you wonder why they recommended you (maybe they’re trying to get something from you…)? Would you think it was a waste that they wrote it now, when you’re not even looking for a new job? Would you wish they had waited until the right time?

Tags: