I use code like this all the time:
myList.sort().each {
// do something
}
Here's a more complex example (to print a list of numbers from 1 to 20
ordered by the number of prime composites):
(1..20).collect {
[
num: it,
factors: PrimeUtils.factor(it) // returns prime factors of it's
arg
]
}.sort { o1, o2 ->
o2.factors.size().compareTo(o1.factors.size())
}.each {
println("${it.num}: ${it.factors}")
}
And the same example written without chaining:
numbers = 1..20
numbers = numbers.collect {
[
num: it,
factors: PrimeUtils.factor(it)
]
}
numbers.sort { o1, o2 ->
o2.factors.size().compareTo(o1.factors.size())
}
numbers.each {
println("${it.num}: ${it.factors}")
}
Each step is certainly more distinct in the second example, but
ultimately the "operation" here is to print the numbers sorted by
number of prime composites, so it's one step. Having it grouped into
a single statement enforces that semantic, and is the best reason to
use chaining if you ask me. Simply to reduce typing isn't a good
reason; coding is about readability and conveying the semantics of the
algorithm as clearly as possible.
cheers,
barneyb
On Tue, Feb 10, 2009 at 11:03 AM, Henry <[email protected]> wrote:
>
> I really don't see the benefit of using Method chaining other than
> jQuery though. jQuery is the only place I use Method chaining. ;-)
>
>
> Henry Ho
>
--
Barney Boisvert
[email protected]
http://www.barneyb.com/
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups
"CFCDev" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/cfcdev?hl=en
-~----------~----~----~----~------~----~------~--~---