<commit_before>= Final Destination
:hp-tags: programming, Java, final, immutability

This is the second installment in the _How to Make Your Java Code Not Suck_ series.

== Fightin' (key)words

When debating Java code style, the one issue that has probably gotten me into the greatest number of heated arguments is the appropriate use of the keyword `final`. I am not alone in my views on the subject, but it seems that there are great unwashed masses of developers who have not yet been converted to the *Church of `final`*, and some of them seem to get quite annoyed when they see `final` used in places where it is not absolutely required.

However, before I go into detail on what my exact position is on the subject, and why nonbelievers are doomed to burn in Mutability Hell, let's recap what, exactly, `final` means when it appears in Java code.

== Keyword Overload

First of all, any Java programmer worth his or her salt knows that `final` actually has two completely different meanings in Java, depending on where it is used.

The first, and probably most commonly used, meaning of `final` is as a modifier on declarations variables, fields, and parameters. When applied in front of one of these, it effectively makes the identifier a constant for the duration of his scope. This means that once the identifier is initialized, the value it refers to cannot be changed. Its use is generally mandated when defining constants (especially in conjuction with the `static` keyword), and prior to Java 8, its use was required by the compiler whenever an anonymous class creates a closure around a variable in the enclosing scope. For primitives, the use of `final` effectively makes the variable a true constant (within its scope), but when applied to objects, it only makes the reference constant, but not the object itself, so care must be taken to not confuse the two concepts.

The second, less commonly used (and probably less well understood), meaning of `final` is as a modifier on classes and methods to restrict inheritance and method overriding. Applying `final` to a class prevents the creation of subclasses that extend it. Applying `final` to a method prevents subclasses from overriding that method.

I am primarily concerned with the first meaning of `final` in this article, though I will touch on the second a bit as well.

== `final` Thesis

Now that we have covered the meanings of `final`, we come back to the subject of when it ought to be used.

After experimenting with different styles over the course of several years, I have settled upon the strongly held conviction that *`final` should be applied to _all_ fields, parameters, and variables except for cases where the value definitely needs to change over time* (and only after considering the alternatives). The sole exceptions to this rule are constants defined on interfaces, which are implicitly `final` without needing to use the keyword, and parameters of abstract methods, where `final` has no effect.

== Preemptive Strike

Before I go on to answer the question of "Why?", I will first preemptively counter the reasons I've heard for "Why not?".

The most common argument against that I've heard when I have argued in favor of liberal use of `final` is that it "clutters up" the code with all those "extra" keywords. To that I have the following things to say:

1. It's only an extra 5 characters (6 if you count the space). It's not like there's a worldwide letter shortage or something. There's a little extra typing involved, but it's not so much as to be cumbersome.
2. In an IDE or a text editor with Java syntax highlighting, those `final` keywords at the beginnings of lines will appear in a different color than the surrounding text, providing you with  nice visual markers of where your variable declarations are.
3. If you're concerned about verbose source code, Java is _not_ the language for you. Address all complaints to <NAME>.
4. Purely cosmetic concerns take a back seat to functional ones.

== On a Soapbox

Now that's I've gotten that out of the way, it's time to explain why you should be using `final` wherever you can.

The first, and perhaps most obvious, or at least most often cited, reason for using `final` extensively is that it enables the compiler to catch cases where you unintentionally change a value that you didn't intend to, due a copy and paste error or because you simply mistyped or confused two identifiers. This "eliminating a class of errors" argument is certainly valid and important, however, it is frequently over-cited by proponents of `final` and may be found unconvincing by those who would counter that such errors would likely be caught by unit tests anyway.

What's more important is the knowledge that the compiler _will_ catch such issues. When you declare a variable to be `final`, or when you're reading someone else's code and see a `final` variable, you can be confident that it always points to the same thing for its entire lifetime. 

== Stuff and Nonsense

Note that I haven't listed performance as a motivating use of `final`. In discussions of `final`, some people erroneously claim that using `final` enables the compiler to implement optimizations that it would not be able to perform on mutable values. This is simply not true. The compiler _can_ apply such optimizations, but it doesn't need you to tell it what values are immutable. The Java compiler can analyze code and figure out which variables are "effectively `final`" all on its own without your help.

The reason that I bring this up is that some people use the fact that the above claim is erroneous as evidence _against_ using `final`, on the grounds that it is unnecessary to achieving performance optimizations. The reasons for using `final` have nothing to do with performance and have everything to do with improving the reliability and maintainability of your code.<commit_msg>Update 2016-04-19-Final-Destination.adoc<commit_after>= Final Destination
:hp-tags: programming, Java, final, immutability

This is the second installment in the _How to Make Your Java Code Not Suck_ series.

== Fightin' (key)words

When debating Java code style, the one issue that has probably gotten me into the greatest number of heated arguments is the appropriate use of the keyword `final`. I am not alone in my views on the subject, but it seems that there are great unwashed masses of developers who have not yet been converted to the *Church of `final`*, and some of them seem to get quite annoyed when they see `final` used in places where it is not absolutely required.

However, before I go into detail on what my exact position is on the subject, and why nonbelievers are doomed to burn in Mutability Hell, let's recap what, exactly, `final` means when it appears in Java code.

== Keyword Overload

First of all, any Java programmer worth his or her salt knows that `final` actually has two completely different meanings in Java, depending on where it is used.

The first, and probably most commonly used, meaning of `final` is as a modifier on declarations variables, fields, and parameters. When applied in front of one of these, it effectively makes the identifier a constant for the duration of his scope. This means that once the identifier is initialized, the value it refers to cannot be changed. Its use is generally mandated when defining constants (especially in conjuction with the `static` keyword), and prior to Java 8, its use was required by the compiler whenever an anonymous class creates a closure around a variable in the enclosing scope. For primitives, the use of `final` effectively makes the variable a true constant (within its scope), but when applied to objects, it only makes the reference constant, but not the object itself, so care must be taken to not confuse the two concepts.

The second, less commonly used (and probably less well understood), meaning of `final` is as a modifier on classes and methods to restrict inheritance and method overriding. Applying `final` to a class prevents the creation of subclasses that extend it. Applying `final` to a method prevents subclasses from overriding that method.

I am primarily concerned with the first meaning of `final` in this article, though I will touch on the second a bit as well.

== `final` Thesis

Now that we have covered the meanings of `final`, we come back to the subject of when it ought to be used.

After experimenting with different styles over the course of several years, I have settled upon the strongly held conviction that *`final` should be applied to _all_ fields, parameters, and variables except for cases where the value definitely needs to change over time* (and only after considering the alternatives). The sole exceptions to this rule are constants defined on interfaces, which are implicitly `final` without needing to use the keyword, and parameters of abstract methods, where `final` has no effect.

== Preemptive Strike

Before I go on to answer the question of "Why?", I will first preemptively counter the reasons I've heard for "Why not?".

The most common argument against that I've heard when I have argued in favor of liberal use of `final` is that it "clutters up" the code with all those "extra" keywords. To that I have the following things to say:

1. It's only an extra 5 characters (6 if you count the space). It's not like there's a worldwide letter shortage or something. There's a little extra typing involved, but it's not so much as to be cumbersome.
2. In an IDE or a text editor with Java syntax highlighting, those `final` keywords at the beginnings of lines will appear in a different color than the surrounding text, providing you with  nice visual markers of where your variable declarations are.
3. If you're concerned about verbose source code, Java is _not_ the language for you. Address all complaints to <NAME>.
4. Purely cosmetic concerns take a back seat to functional ones.

== On a Soapbox

Now that's I've gotten that out of the way, it's time to explain why you should be using `final` wherever you can.

The first, and perhaps most obvious, or at least most often cited, reason for using `final` extensively is that it enables the compiler to catch cases where you unintentionally change a value that you didn't intend to, due a copy and paste error or because you simply mistyped or confused two identifiers. This "eliminating a class of errors" argument is certainly valid and important, however, it is frequently over-cited by proponents of `final` and may be found unconvincing by those who would counter that such errors would likely be caught by unit tests anyway.

What's more important is the knowledge that the compiler _will_ catch such issues. When you declare a variable to be `final`, or when you're reading someone else's code and see a `final` variable, you can be confident that the identifier always points to the same thing for its entire lifetime. This means that if you see the identifier used in an expression somewhere, you need only go back to the line where it was initialized to find out its value. This saves you the trouble of needing to scrutinize every line of a method to determine whether its value may have changed at any point, and gives you the peace of mind of knowing that you didn't overlook such a line. When `final` is applied consistently, this helps you to debug problems by allowing you to more quickly narrow down the possible causes, and it helps developers who have not seen the code before (or recently) to more easily understand what it does.

A benefit of somewhat lesser importance but still valuable comes about when `final` is always used whenever it can be used throughout a codebase. In such a project, any variable that is _not_ marked `final` is immediately noticeable as something special (i.e., intentionally mutable) and therefore warranting further scrutiny by anyone reading the code. If you're used to seeing `final` variables, fields, and parameters everywhere and spot one that isn't `final`, you are likely to immediately go looking for the lines of code where its value is being changed and determining why.

== Stuff and Nonsense

Note that I haven't listed performance as a motivating use of `final`. In discussions of `final`, some people erroneously claim that using `final` enables the compiler to implement optimizations that it would not be able to perform on mutable values. This is simply not true. The compiler _can_ apply such optimizations, but it doesn't need you to tell it what values are immutable. The Java compiler can analyze code and figure out which variables are "effectively `final`" all on its own without your help.

The reason that I bring this up is that some people use the fact that the above claim is erroneous as evidence _against_ using `final`, on the grounds that it is unnecessary to achieving performance optimizations. The reasons for using `final` have nothing to do with performance and have everything to do with improving the reliability and maintainability of your code.
{'fraction_non_alphanumeric': 0.0378009507744211, 'fraction_numerical': 0.001686857843888974, 'mean_word_length': 4.57631466438649, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '809676', 'n_tokens_mistral': 3027, 'n_tokens_neox': 2870, 'n_words': 2178}