简体   繁体   English

方法参数应该在Java8中作为final

[英]Should method parameters be made as final in Java8

In java8, variables are effectively final if we do not assign them again. 在java8中,如果我们不再分配它们,变量实际上是最终的。 So, it means if we are declaring a method and if we don't declare its parameters to be final, then they are effectively final if we don't assign them in the method definition. 因此,这意味着如果我们声明一个方法,并且如果我们不声明它的参数是最终的,那么如果我们不在方法定义中分配它们,它们实际上是最终的。 So, does making the parameters final make any difference in java8? 那么,使参数最终在java8中有什么不同吗?

IMO, the reason to mark a parameter final is to show that you are depending on it being final. IMO,标记最终参数的原因是为了表明你依赖它是最终的。 This might be the case if you are using the parameter in a lambda expression or an inner class. 如果您在lambda表达式或内部类中使用参数,则可能就是这种情况。 Marking the parameter final tells the next programmer who comes along (or you a year from now) that there is code that relies on that parameter being final. 标记参数final告诉下一个程序员(或者从现在开始一年),有代码依赖于该参数是最终的。

No. it isn't effectively final unless you use it inside anonymous function or lambda expression. 不,除非你在匿名函数或lambda表达式中使用它,否则它不是最终的。 Not in normal methods, why should it be. 不是正常的方法,为什么要这样。

I use final the same way as you. 我以与你相同的方式使用final。 To me it looks superfluous on local variables and method parameters, and it doesn't convey useful extra information. 对我来说,局部变量和方法参数看起来多余,而且它没有传达有用的额外信息。

One important thing is that strive to keep my methods short and clean, each doing a single task. 一个重要的事情是努力保持我的方法简洁,每个人都做一个单一的任务。 Thus my local variables and parameters have a very limited scope, and are used only for a single purpose. 因此,我的局部变量和参数的范围非常有限,仅用于单一目的。 This minimizes the chances of reassigning them inadvertently. 这最大限度地减少了无意中重新分配它们的可能性。

Moreover, as you surely know, final doesn't guarantee that you can't change the value/state of a (nonprimitive) variable. 而且,正如您所知,final并不能保证您不能更改(非原始)变量的值/状态。 Only that you can't reassign the reference to that object once initialized. 只有在初始化后才能重新分配对该引用的引用。 In other words, it works seamlessly only with variables of primitive or immutable types. 换句话说,它只能与原始类型或不可变类型的变量无缝地协同工作。 Consider 考虑

final String s = "forever";
    final int i = 1;
    final Map<String, Integer> m = new HashMap<String, Integer>();

    s = "never"; // compilation error!
    i++; // compilation error!
    m.put(s, i); // fine

This means that in many cases it still doesn't make it easier to understand what happens inside the code, and misunderstanding this may in fact cause subtle bugs which are hard to detect 这意味着在许多情况下它仍然不会让人更容易理解代码中发生的事情,而误解这可能实际上会导致难以察觉的细微错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM