02 October 2013

Groovy - say NO to FOR loops

Although for loops are part of Groovy, the each iterator is much more useful.  I just found this out from a developer at my job.

I have been doing a pretty big project. Part of the project involves having a grails application run a job every min. each time it runs this job, it will iterate through a set of IP's.  Each IP is a proxy that routes a telephone call. If the call completes it pass's, if it doesn't, we through a failure.  Each iteration needs to be stored in the database.

The problem was this....

I had a For loop that would create a new instance, then do the validation... But each run would replace the results in the db. 

By switching to an each closure, it resolved this.  Here's some example code of what worked:

ipprox = ["127.0.0.1","128.0.0.1","129.0.0.1"]
ipprox.each { prox - def res = proxyCheckService.sipp(phone,proxy).result def proxyCheckInstance = new ProxyCheck proxyCheckInstance.results = res proxyCheckInstance.dnis = dnis proxyCheckInstance.proxy = prox
if (res =~ /Successful call\s+9[0])\s+1/){ proxyCheckInstance.pass = "PASS" } else { proxyCheckInstance.pass="FAIL" }
proxyCheckInstance.save(flush:true)

In this code, I no longer had the problem of iterating through a list and getting one db record at the end.  Now, the list is correctly being iterated through, each run gets it's own db row entry.

Thanks Yakoob for your help!