Bridging the Dynamic Gap
Join the DZone community and get the full member experience.Join For Free
Type inferenceImagine you define an untyped variable a in Groovy, like this:
def a ='Groovy is fantastic'
Thanks to type inference the IDE knows that a contains a string value and so it can provide String-specific code completion for the variable.
Plus it will be able to differentiate between methods that exist on the String class and those that don't by underlining the invalid method's name.
If a no longer contains a string value and is assigned let say an integer, the String-specific methods after the re-assignment are underlined as undefined and they are not offered in the code-completion box any more.
In more complex scenarios type inference can help the static code analysis tools detect potential problems and highlight them in the code. It's not a complete replacement for compile-time type checking, but it definitely helps avoid a great number of type errors.
Dynamic method dictionary
Those, who've tried programming in Groovy know that it is a lot of fun. And doing meta-programming in Groovy is even more fun. You can do things like, for example, define a new method on the String class at runtime.
However, using the dynamically defined methods is not as convenient as using normal methods. The hasUpperChars() method is not available in the code-completion box. And if you call the method on a String variable, it gets underlined as being undefined and thus potentially suspicious. I don't like suspicious code in my applications nor I like to see false warnings. The IDE has no direct way to ensure that the hasUpperChars() method exists on the String class at the point of calling it, though. Shall we ban meta-programming? Or shall we live without code completion and verification?
I'd voted for the second option until recently. A couple of weeks ago I realized that I can use a new feature in JetGroovy, the Groovy plugin for IntelliJ IDEA, which allows me to store my dynamic methods in a custom dictionary of dynamic methods.
The methods in the dictionary are used to both populate the code-completion box and to validate called methods for existence. And this is of great help.
Although I still miss the compile-time type-safety of Java while coding in Groovy, now with the improving IDE support I feel more confident about my code.
Note: The post was originaly posted on my blog.
Opinions expressed by DZone contributors are their own.