简体   繁体   中英

Should method parameters be made as final in Java8

In java8, variables are effectively final if we do not assign them again. 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?

IMO, the reason to mark a parameter final is to show that you are depending on it being final. This might be the case if you are using the parameter in a lambda expression or an inner class. 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.

No. it isn't effectively final unless you use it inside anonymous function or lambda expression. Not in normal methods, why should it be.

I use final the same way as you. 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. 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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