Analytics

Wednesday, September 21, 2011

4 Groovy Tips You May Not Know

I have been programming in Groovy full time for almost two years now, and I feel quite comfortable with it. In fact, the language's idioms, shortcuts, and syntax has become part of my daily programming thinking. This is fantastic as it has opened my mind to unique programming elegance and artistry, but unfortunately on the flip-side it has cause me to cringe when looking at traditional Java code. This speaks to the efficiency and conciseness of Groovy.

Recently I decided that even though I am adequetely familiar with the language, I wanted to read Programming In Groovy by Venkat Subramanium. I was pleasantly surprised that I learned some useful tips. Below are some tips that I learned:

1. Variant Looping Mechanisms

In addition to the traditional looping constructs, such as "for (i in iterm)" or range (0..5), Groovy provides alternate ways to loop.

Use the upto function to operate on a range of values:
def sum = 0
10.upto(15) {
  sum += it
}
println sum

result:
75


Use the step function to skip values:
3.step(20, 3) {
  print "$it "
}

result:
3 6 9 12 15 18 


2. String Literals vs String Expressions

In Groovy, you can define a String in a few ways: with a single quote or double quote. But what is the difference? The single quote is a literal and the second is an expression. A literal takes what is inside of it and accepts it literally, never evaluating it. A double qoute is an expression, and whatever is inside is evaluated.

A literal takes exactly what is inside.
def myName = "Nirav"
print 'This is my name: ${myName}'

result:
This is my name: ${myName}


A literal can come in handy if you want to avoid using escape characters to clutter up code.

An expression evaluates a variable.
def myName = "Nirav"
print "This is my name: ${myName}"

result:
This is my name: Nirav


3. String Convenience Methods

There are some handy methods on Strings in Groovy.

A multi-line string can give clarity to your code. I find it handy when describing an sql expression.
""" select * 
    from person 
    where name = 'Bob' """


Use overloaded methods in String to manipulate the string.
def sentence = "I am tired of all the damn crap in politics"
sentence -= "damn crap" // remove the potty mouth
sentence += ", but I still like Obama"
println sentence

result:
I am tired of all the  in politics, but I still like Obama


4. Groovy Truth

Groovy truth can provide problems if you are not aware of it. However, you can use it to your advantage to reduce code. Essentially, groovy truth evaluates anything with a value populated to 'true', while evaluating anything empty or null to 'false'.
groovyTruthTester(0)
groovyTruthTester(1)
groovyTruthTester([])
groovyTruthTester(null)
groovyTruthTester("")
groovyTruthTester("hello")

if (value) {
    println "${value} evaluated to true"
}
else {
    println "${value} evaluated to false"
}

result:
0 evaluated to false
1 evaluated to true
[] evaluated to false
null evaluated to false
 evaluated to false
hello evaluated to true

8 comments:

  1. Hi! Nice post.

    I know your first example is about iterating but it could be simplified.

    def sum = (10..15).inject(0) { s, i -> s += i }
    println sum //75

    or

    def sum = (10..15).sum()
    println sum //75

    With groovy, a lot of times you find that you really don't need to iterate and change a variable.

    ReplyDelete
  2. Thanks that's a good suggestion. Yes upto is one of many ways to iterate. can you think of any unique ways to use upto?

    ReplyDelete
  3. Hi Nirav, here is a shorter truthTester, although not as clear for novices.

    def groovyTruthTester = { value ->
    println "${value} evaluated to ${value as boolean}"
    }

    ReplyDelete
  4. Thanks for sharing this informative content , Great work
    Leanpitch provides online training in Advanced Scrum Master during this lockdown period everyone can use it wisely.
    Advanced Scrum Master Training Online

    ReplyDelete
  5. Thanks for sharing this informative content , Great work
    Leanpitch provides online training inScrum Master during this lockdown period everyone can use it wisely.
    Advanced Scrum Master Training

    ReplyDelete
  6. Thanks for sharing this informative content , Great work
    Leanpitch provides online training inScrum Master during this lockdown period everyone can use it wisely.
    Advanced Scrum Master Training

    ReplyDelete
  7. This article was very informative and helpful thank you very much for sharing. Yellowstone Coat

    ReplyDelete
  8. Thank you for giving the great article. It delivered me to understand several things about this concept. Keep posting such surpassing articles so that I gain from your great post.
    ibm full form in india |
    ssb ka full form |
    what is the full form of dp |
    full form of brics |
    gnm nursing full form |
    full form of bce |
    full form of php |
    bhim full form |
    nota full form in india |
    apec full form |

    ReplyDelete