将常量变量标为常量是否有意义? [英] Does it make sense to mark variable as final in groovy?

查看:139
本文介绍了将常量变量标为常量是否有意义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道标记为 final 的变量是如何被Groovy解释的(在1.8.0,1.8.1中)。我知道它在Java中是有意义的,并且可以提高性能,当然也可以帮助避免愚蠢的错误。我想了解 final 是否可以帮助java编译器优化用Groovy编写的程序。我想知道Groovy变换器是否保留变量的 final 标记。 如果编译器为最终变量执行的优化对你很重要,那么你不应该使用Groovy。



然而,如果Groovy的性能足够好,那么最终标记变量仍然很有用,原因有两个:


  • 保护你的类的不变量,即确保在构造对象后不能改变一个值。 Java在编译时强制执行此操作,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.

解决方案

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

这篇关于将常量变量标为常量是否有意义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆