Style guide

A Java developer embarking on a Groovy adventure will always have Java in mind, and will progressively learn Groovy,
one feature at a time, becoming more productive and writing more idiomatic Groovy code.
This document’s purpose is to guide such a developer along the way, teaching some common Groovy syntax style,
new operators, and new features like closures, etc.
This guide is not complete and only serves as a quick intro and a base for further guideline sections
should you feel like contributing to the document and enhancing it.

1. No semicolons

When coming from a C / C++ / C# / Java background, we’re so used to semicolons, that we put them everywhere.
Even worse, Groovy supports 99% of Java’s syntax, and sometimes,
it’s so easy to paste some Java code into your Groovy programs, that you end up with tons of semicolons everywhere.
But…​ semicolons are optional in Groovy, you can omit them, and it’s more idiomatic to remove them.

2. Return keyword optional

In Groovy, the last expression evaluated in the body of a method can be returned without necessitating the return keyword.
Especially for short methods and for closures, it’s nicer to omit it for brevity:

In such case, either putting a newline before the last expression, or explicitly using return may yield better readability.

I, for myself, sometimes use the return keyword, sometimes not, it’s often a matter of taste.
But often, inside of closure, we omit it more often than not, for example. So even if the keyword is optional,
this is by no means mandatory to not use it if you think it halters the readability of your code.

A word of caution, however. When using methods which are defined with the def keyword instead of a specific concrete type,
you may be surprised to see the last expression being returned sometimes. So usually prefer using a specific return type like void or a type.
In our example above, imagine we forgot to put m2 as last statement to be returned,
the last expression would be m2.c = 3, which would return…​ 3, and not the map you expect.

Statements like if/else, try/catch can thus return a value as well, as there’s a "last expression" evaluated in those statements:

3. Def and type

As we’re talking about def and types, I often see developers using both def and a type. But def is redundant here.
So make a choice, either use def or a type.

So don’t write:

def String name = "Guillaume"

But:

String name = "Guillaume"

When using def in Groovy, the actual type holder is Object (so you can assign any object to variables defined with def,
and return any kind of object if a method is declared returning def).

When defining a method with untyped parameters, you can use def but it’s not needed, so we tend to omit them.
So instead of:

void doSomething(def param1, def param2) { }

Prefer:

void doSomething(param1, param2) { }

But as we mention in the last section of the document, it’s usually better to type your method parameters,
so as to help with documenting your code, and also help IDEs for code-completion,
or for leveraging the static type checking or static compilation capabilities of Groovy.

Another place where def is redundant and should be avoided is when defining constructors:

class MyClass {
def MyClass() {}
}

Instead, just remove the def:

class MyClass {
MyClass() {}
}

4. Public by default

By default, Groovy considers classes and methods public.
So you don’t have to use the public modifier everywhere something is public.
Only if it’s not public, you should put a visibility modifier.

You may wonder about the 'package-scope' visibility,
and the fact Groovy allows one to omit 'public' means that this scope is not supported by default,
but there’s actually a special Groovy annotation which allows you to use that visibility:

class Server {
@PackageScope Cluster cluster
}

5. Omitting parentheses

Groovy allows you to omit the parentheses for top-level expressions, like with the println command:

println "Hello"
method a, b

vs:

println("Hello")
method(a, b)

When a closure is the last parameter of a method call, like when using Groovy’s each{} iteration mechanism,
you can put the closure outside the closing parentheses, and even omit the parentheses:

7. Getters and Setters

In Groovy, a getters and setters form what we call a "property",
and offers a shortcut notation for accessing and setting such properties.
So instead of the Java-way of calling getters / setters, you can use a field-like access notation:

As you can see, a free standing 'field' without modifier visibility actually
makes the Groovy compiler to generate a private field and a getter and setter for you.

When using such POGOs from Java, the getter and setter are indeed there, and can be used as usual, of course.

Although the compiler creates the usual getter/setter logic,
if you wish to do anything additional or different in those getters/setters,
you’re free to still provide them, and the compiler will use your logic, instead of the default generated one.

8. Initializing beans with named parameters and the default constructor

You can use named parameters with the default constructor (first the constructor is called, then the setters are called in the sequence in which they are specified in the map):

def server = new Server(name: "Obelix", cluster: aCluster)

9. Using with() for repeated operations on the same bean

Named-parameters with the default constructor is interesting when creating new instances,
but what if you are updating an instance that was given to you, do you have to repeat the 'server' prefix again and again?
No, thanks to the with() method that Groovy adds on all objects of any kind:

10. Equals and ==

To compare the references of objects, instead of ==, you should use a.is(b).

But to do the usual equals() comparison, you should prefer Groovy’s ==,
as it also takes care of avoiding NullPointerException, independently of whether the left or right is null or not.

Instead of:

status != null && status.equals(ControlConstants.STATUS_COMPLETED)

Do:

status == ControlConstants.STATUS_COMPLETED

11. GStrings (interpolation, multiline)

We often use string and variable concatenation in Java, with many opening / closing of double quotes, plus signs,
and \n characters for newlines.
With interpolated strings (called GStrings), such strings look better and are less painful to type:

throw new Exception("Unable to convert resource: " + resource)

vs:

throw new Exception("Unable to convert resource: ${resource}")

Inside the curly braces, you can put any kind of expression, not just variables.
For simple variables, or variable.property, you can even drop the curly braces:

throw new Exception("Unable to convert resource: $resource")

You can even lazily evaluate those expressions using a closure notation with ${-> resource }.
When the GString will be coerced to a String, it’ll evaluate the closure and get the toString() representation of the return value.

throw new PluginException("Failed to execute command list-applications:" +
" The group with name " +
parameterMap.groupname[0] +
" is not compatible group of type " +
SERVER_TYPE_NAME)

You can use the \ continuation character (this is not a multiline string):

throw new PluginException("Failed to execute command list-applications: \
The group with name ${parameterMap.groupname[0]} \
is not compatible group of type ${SERVER_TYPE_NAME}")

Or using multiline strings with triple quotes:

throw new PluginException("""Failed to execute command list-applications:
The group with name ${parameterMap.groupname[0]}
is not compatible group of type ${SERVER_TYPE_NAME)}""")

You can also strip the indentation appearing on the left side of the multiline strings by calling .stripIndent() on that string.

Also note the difference between single quotes and double quotes in Groovy: single quotes always create Java Strings,
without interpolation of variables, whereas double quotes either create Java Strings or GStrings when interpolated variables are present.

For multiline strings, you can triple the quotes: i.e. triple double quotes for GStrings and triple single quotes for mere Strings.

If you need to write regular expression patterns, you should use the "slashy" string notation:

assert "foooo/baaaaar" ==~ /fo+\/ba+r/

The advantage of the "slashy" notation is that you don’t need to double escape backslashes, making working with regex a bit simpler.

Last but not least, prefer using single quoted strings when you need string constants,
and use double quoted strings when you are explicitly relying on string interpolation.

12. Native syntax for data structures

Groovy provides native syntax constructs for data structures like lists, maps, regex, or ranges of values.
Make sure to leverage them in your Groovy programs.

13. The Groovy Development Kit

Continuing on the data structures, when you need to iterate over collections,
Groovy provides various additional methods, decorating Java’s core data structures,
like each{}, find{}, findAll{}, every{}, collect{}, inject{}.
These methods add a functional flavor to the programming language and help working with complex algorithms more easily.
Lots of new methods are applied to various types, through decoration, thanks to the dynamic nature of the language.
You can find lots of very useful methods on String, Files, Streams, Collections, and much more:

You’ll also notice the nice output that Groovy’s "Power Assert" statement provides,
with a graph view of the various values of each sub-expressions being asserted.

19. Elvis operator for default values

The Elvis operator is a special ternary operator shortcut which is handy to use for default values.

We often have to write code like:

def result = name != null ? name : "Unknown"

Thanks to Groovy Truth, the null check can be simplified to just 'name'.

And to go even further, since you return 'name' anyway, instead of repeating name twice in this ternary expression,
we can somehow remove what’s in between the question mark and colon, by using the Elvis operator, so that the above becomes:

def result = name ?: "Unknown"

20. Catch any exception

If you don’t really care about the type of the exception which is thrown inside your try block,
you can simply catch any of them and simply omit the type of the caught exception.
So instead of catching the exceptions like in:

try {
// ...
} catch (Exception t) {
// something bad happens
}

Then catch anything ('any' or 'all', or whatever makes you think it’s anything):

try {
// ...
} catch (any) {
// something bad happens
}

Note that it’s catching all Exceptions, not `Throwable`s. If you need to really catch "everything",
you’ll have to be explicit and say you want to catch `Throwable`s.

21. Optional typing advice

I’ll finish on some words on when and how to use optional typing.
Groovy lets you decide whether you use explicit strong typing, or when you use def.

I’ve got a rather simple rule of thumb: whenever the code you’re writing is going to be used by others as a public API,
you should always favor the use of strong typing, it helps making the contract stronger,
avoids possible passed arguments type mistakes, gives better documentation, and also helps the IDE with code completion.
Whenever the code is for your use only, like private methods,
or when the IDE can easily infer the type, then you’re more free to decide when to type or not.