4 ms·
All variables in Java must be final
- Confusion 17y agoAs argued in, for instance, Hardcore Java[1], 'final' should definitely have been the default for variables in Java. My Eclipse 'on save' actions include making every possible local variable, parameter and field final. If I'm reading the code and one of them is not final, I know it requires some extra attention. [1] http://oreilly.com/catalog/9780596005689 http://oreilly.com/catalog/9780596005689
- Retric 17y agoWhat is wrong with loops?
- Confusion 17y ago:). I didn't mean it like that. I meant that when I'm reading code, I know to pay extra attention when something is not final. There will always be non-final variables around, for instance 'previousItem' to track the previous item through a loop. Added some words to the parent to clarify.
- bokchoi 17y agoPerhaps we should go even farther -- 'final' should be default on methods and classes as well. Derivation should only be allowed where explicitly granted by a programmer.
- alrex021 17y ago... and all methods must be static with no side effects. Additionally, use functors to simulate crippled closures and you have a broken FP paradigm embedded in you cup of Java.
- Confusion 17y ago... and ridicule the article/Java, instead of acknowledging that it rightly argues that the average Java program benefits from less occasions for mutability.
- viraptor 17y agoIt might rightly argue that. But java suffers from being too verbose and not flexible enough. Now someone proposes to add another keyword to 99% of declarations to make java act in a similar to what some other languages do by default. Maybe you should just use another language if state (i.e. the standard way of programming in java) bothers you that much?
- Confusion 17y agoMaybe you should just use another language [..] Believe me, I'm trying :)
- alrex021 17y agoI acknowledge the author's arguments and recommendations. However, I do feel I have the right to exercise my freedom of speech, even if its tongue-in-cheek. That said, my view is that Java, the language, has some deeply rooted flaws.
- proemeth 17y agoWhat about loop variables? Want to re-allocate them at each step?
- Tichy 17y agoWant to succeed? Try failing... SCNR... Seriously, though, I've come to think of Java as "fear driven development".
- Confusion 17y agoSomeone advocates less mutability and instead of applauding that, you start scoffing Java. Is Lisp a fearful language?
- Tichy 17y agoIt's not really the mutability I don't like about Java anymore. I don't have enough experience with immutability, except for doing some Project Euler problems in Erlang. There I kind of hit a wall trying to compute primes efficiently (the seave was not possible with immutable lists).
- mpobrien 17y agoExcept newbie programmers should keep in mind that final is not simply synonymous with immutability. final ArrayList x = new ArrayList(); // x is final, so it can't be reassigned x.add( "foo" ); // but we can still modify its contents
- city41 17y agoIt is synonymous with immutability though, in the strictest sense. In this case x and the ArrayList are two different things, one is final, the other is not. Yeah it's an anal distinction, but still a valid one.
- nradov 17y agoThe java.util.Collections class has several methods for making collection objects immutable. I use those whenever possible. Of course that only prevents changes to the collection, it doesn't prevent changes to individual collection elements. http://java.sun.com/javase/6/docs/api/java/util/Collections.html http://java.sun.com/javase/6/docs/api/java/util/Collections....
- lemming 17y agoIt's worth noting that this doesn't actually provide an immutable collection, it provides an immutable view of an existing one. If some other code has a reference to the underlying collection it can still be mutated. However this works well for the common case where you have a method which creates a local collection and returns the immutable view - in that case the collection is effectively immutable.
- twir 17y agoThis is a great philosophy, but I'd hesitate to say "all" variables; sometimes it just doesn't work out. ex, in class definition: final int foo; In constructor: try { foo = 1; } catch ( Exception e ) { foo = 2; }
- lsb 17y agoIf your try{} catch{} blocks were expressions, not statements, you could write foo = try { 1 } catch(Exception e) { 2 } much like the foo = bool ? 1 : 2 ternary if statement, versus the if() {} else {} clauses.
- twir 17y agoWow, never knew one could do that.
- nradov 17y agoYou can't do that. It would require a language change, to make try/catch blocks expressions.
- twir 17y agoHeh, I didn't think so. ;)
- eldenbishop 17y agoYou can sort of do this in Groovy. def val = {try { 1 } catch(ex) { 2 }}.call() assert(1 == val)
- nradov 17y agoIn cases like that I usually exact the try/catch block into a separate private method which returns an int. Then the constructor can just call that method and use the return value to set foo.
- city41 17y agoThe final keyword in Java is great. It's probably the only design decision I think Java really got right compared to C# (sealed, readonly, const? bleh)
- jefffoster 17y agoIt's a poor substitute for C++'s const though - at least that lets you reason about the state of an object. Java's final keyword just stops you reassigning a reference - how many times do you inadvertently do that?
- jgrant27 17y agoThe very first code snippet is NOT valid Java and yet the author claims decades of programming experience (about page). He also seems to have very recently discovered the side-effects of imperative programming.
- j_baker 17y agoI'll agree that all variables should be final. However, you're applying a functional constraint (that most functional languages provide workarounds for) to an imperative language. I just don't feel it's reasonable to expect a java programmer to obey rules that languages like ocaml don't even enforce 100%.
- lemming 17y agoThis article fails to mention the main benefit of final - it gives you much stricter guarantees for concurrency under the Java Memory Model. If you create an immutable object and the fields are final, you can immediately pass the object to another thread without synchronisation - this is not safe if the fields are not final but are otherwise immutable. For this reason we enforce that all object member fields must be final if possible, but we don't enforce it for local variables or method parameters. There are benefits to be had by doing that as well but IMO the benefit outweighs the return (and our IDE, IntelliJ, warns us if we reuse a local variable or method parameter).