Re: Ted Neward on anonymous generic methods


C#'s fanatic Ted Neward is amazed at how cool C#'s anonymous generic methods are. He then gives an example of a little program that filters some entries according to a critiria, using some generic types and delegates. It's about finding all persons from a set of persons whose last name is "Neward". Sam Pullara even showed his own version of the same program in Java and explains that IntelliJ IDEAallowed him to type roughly 10% of the characters of the program thanks to the wonderful completion and code templating capabilities of that IDE.

What strikes me is how verbose both versions are. Even C# with its delegate isn't particularly less verbose, except a few lines saved. No real readability, expressiveness or productivity gained -- though I must confess I do like all those nifty little features available in the upcoming C# 3.0. Naturally, I was tempted to give my own Groovy version of the problem. Here it is, and please note the conciseness and clarity of the following code:

class Person {
    @Property String firstName
    @Property String lastName
    @Property int age
    String toString() { "Person{firstName='$firstName', lastName='$lastName', age=$age}" }
}

def persons = [
    new Person(firstName: "Cathi", lastName: "Gero", age: 35),
    new Person(firstName: "Ted", lastName: "Neward", age: 35),
    new Person(firstName: "Stephanie", lastName: "Gero", age: 12),
    new Person(firstName: "Michael", lastName: "Neward", age: 12),
]

def newards = persons.findAll{ it.lastName == "Neward" }

newards.each{ println it }

 

 
© 2012 Guillaume Laforge | The views and opinions expressed here are mine and don't reflect the ones from my employer.