Search code examples
optimizationgroovyfinal

Does it make sense to mark variable as final in groovy?


I wonder how variables marked as final are interpreted by Groovy (in 1.8.0, 1.8.1). I know that it makes sense in Java and it is possible to improve the performance and -- of course -- help to avoid stupid mistakes. I would like to learn if final may help the java compiler to optimize a program written in Groovy. I wonder if Groovy transformers preserve the final markings for variables.


Solution

  • As Justin has said, if the optimisations that the compiler performs for final variables are important to you, then you shouldn't be using Groovy.

    However, if the performance of Groovy is good enough, then it is still useful to mark variables final for two reasons:

    • Protecting your class' invariants, i.e. making sure that a value cannot be changed after object construction. Java enforces this at compile-time, Groovy only enforces this at runtime, but this is better than silently allowing an immutable value to be changed

    • Documentation. Users of your class can easily see which values they are allowed to change