3.7 Dynamic: To Be or Not to Be?
Given that Groovy is a dynamically typed language that supports optional typing, should we specify the type or rely on dynamic typing? There are no real rules in this area, but we can certainly develop some preferences.
When programming in Groovy, I lean toward omitting the type and instead making the parameter/variable names very expressive. Not specifying the type has the added advantages of duck typing (Section 3.4, Design by Capability) and the ease of applying mocks for testing (Section 18.2, Unit Testing Java and Groovy Code).
I opt to specify the type if I am forced to, like when JUnit requires test methods to be void or when specificity provides a significant benefit, like when mapping types ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access