Declaring things final in Java

This is probably a really weird thing to be blogging about. I mean: whats to know, really? The “final” keyword is a pretty underused feature of Java. It’s most common (for some people it’s only use) is for static fields:

public static final int ONE = 1;

However, there are several tricks to final that some people know nothing about. For example: when used on a field, you don’t have to assign a value immediately. Amazingly, the following code is in fact valid:

public class NumberStringThingy {
private final String value;

public NumberStringThingy(int number) {
if(number < 0) { value = "negative"; } else { value = Integer.toString(number); } } } [/sourcecode] This is a really awful example in some ways, but it serves the point. You can make a decision in the constructor about what to the field, so long as every possible branch leads to the field being assigned. You can also declare local variables and parameters as final. The final keyword can serve as a hint to the Hotspot compiler at runtime. In some ways the opposite to volatile. There is another, much more important reason to declare fields, variables and parameters (almost all of them in fact) as final:

It makes your code more readable.

I started experimenting a few months ago, declaring anything that didn’t change value as final. The result: I can read my code much faster now, and my older code? When I see things that could be final, I’ve started changing them. It’s a massive psychological effect it has: if a variable isn’t final, it must change somewhere. It means that with a glance at the code, you can be very certain what the value of a variable is.

I strongly recommend giving this a try for a few weeks, you may find it very hard to go back to normal.

Note: I don’t recommend declaring your classes and methods final unless it really makes sense. Just fields, variables and parameters.

Advertisements

One Response to “Declaring things final in Java”

  1. Shriram Says:

    I had been thinking that the idea behind final is to ensure that the variable assigned a value only once.


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: