Groovy is a powerful tool. Like other powerful tools (think of a chainsaw) it requires a certain amount of user expertise and attention. Otherwise, results may be fatal.
Following code fragments are allowed in Groovy but usually result in unintended behaviour or incomprehensible problems. Simply don't do this and spare yourself some of the frustration that new and unskilled Groovy programmers sometimes experience.
1. Accessing an object's type like a property
.class instead of
.getClass() is ok - as long as you know exactly what kind of object you have. But then you don't need that at all. Otherwise, you run in the risk of getting
null or something else, but not the class of the object.
2. Omitting parentheses around method arguments when not appropriate
Better use parentheses for argument lists unless you are sure.
For instance, a left parenthesis after a method name must always enclose the parameter list.
3. Putting a newline at the wrong place into the code
This may cause the compiler to to assume a complete statement although it is meant as continuing in the next line. It is not always as obvious as in the following example.
4. Forgetting to write the second equals sign of the equals operator
As a result, a comparison expression turns into an assignment.
(One measure is to put constant expressions in comparisons always before the equals operator.)
5. Specifying the wrong return type when overriding a method (Groovy version < 1.5.1 only)
Such a method may be considered as overloaded (a different method with the same name) and not be called as expected.
6. Disregarding other objects' privacy
When accessing methods, fields, or properties of other classes, make sure that you do not interfere with private or protected members. Currently Groovy doesn't distinguish properly between public, private, and protected members, so watch out yourself.
7. Thoughtless dynamic programming
Check for conflicts with intended class functionality before adding or changing methods or properties using Groovy's dynamic facilities.
8. String concatenation
As in Java, you can concatenate Strings with the "+" symbol. But Java only needs that one of the two items of a "+" expression to be a String, no matter if it's in the first place or in the last one. Java will use the
toString() method in the non-String object of your "+" expression. But in Groovy, you just should be safe the first item of your "+" expression implements the
plus() method in the right way, because Groovy will search and use it. In Groovy GDK, only the Number and String/StringBuffer/Character classes have the
plus() method implemented to concatenate strings. To avoid surprises, always use GStrings.