Use defined type declarations in favor of dynamic types

   Exchange Pre-configured Maestro services.  |   Platform Developer  |  All versions   This feature is related to v5.1 and higher.

One of the conveniences that Groovy provides is dynamic type assignment. For example, by specifying a variable to be of type def the developer can avoid having to give that variable a definite type and can handle different types at run time.

This is similar (but not exactly the same) as specifying a variable to be of type Object in Java. For example, the following Groovy code compiles without needing to cast the name variable to a String type:

def name = "Stephanie"
println name.toUpperCase() // no cast required

However, in Java you need to explicitly cast the name variable to a String before using a method of the String class:

Object name = "Stephanie";
System.out.println(((String) name).toUpperCase());

However, while this feature may give the coder an immediate convenience, there are a number of key reasons why it is better to use defined types:

  • Make better use of IDE productivity assistants
  • Reduce the chances of bugs
  • Improve the readability of code

Activate IDE Productivity Assistants

IDE's are able to provide better code complete functions and type checking where defined types are used, making development and maintenance of Groovy code far more productive.

In the method declaration below we're expecting the first parameter to be a Map but the IDE does not know that and cannot provide any suggestions as to what functions and attributes are available on that object:

Using defined types activates the IDE productivity assistants:

Reduce the Chances of Run-time Bugs

Using defined types allows the IDE and compilers to identify bugs early so that they can be resolved before the software is deployed and running in a production scenario.

This improves the reliability of the code and reduces the operational burden of dealing with issues in live environments.

Improve the Readability of Code

Defined type declarations make code easier to read and to understand the intention of the code, and helps self-document the code.

Consumers of the code are better informed as to the supported uses of the functions and less inclined to develop unsupported code.

Developers tasked with maintaining the code have a greater understanding of the intended purpose of the code and less inclined to modify the functions to include unintended behaviors.

When does it make sense to use def?

There are some scenarios where it does make sense to use dynamic types, just don't let laziness be the reason to use def.

Use def only if there's no definite type applicable to the variable at compile time.