开发者

Are there any reasons to make all fields and variables final?

In my current project I noticed that all class fields and variable inside methods are declared with final modifier whenever it's possible.

Just like here:

private final XMLStreamWriter _xmlStreamWriter;
private final Marshaller _marshaller;
private final OutputStream _documentStream;

private final OutputStream _stylesStream;
private final XMLStreamWriter _stylesStreamWriter;
private final StyleMerger _styleMerger;

public DocumentWriter(PhysicalPackage physicalPackage) throws IOException {
    final Package pkg = new Package(physicalPackage);

    final Part wordDocumentPart = pkg.开发者_如何学JAVAcreatePart(
            "/word/document.xml",
            "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml",
            "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");

    // styles.xml
    final Pair<Part, String> wordStylesPart = wordDocumentPart.createRelatedPart(...);
    ...
}

Are there any reasons to do so?

p.s. As I know project is not supposed to be multithreaded (at least I've heard nothing about it).


When you write final you are signalling both to the compiler and the human reader that this variable is set once and then not changed.

The compiler uses it to check that you don't accidentally reassign a variable. If you do this it will give a compile error.

The human reader can use it to understand the intention of the code more quickly.

Missing it out typically won't cause your code to fail, but if you want a field to not change it is a good idea to say that explicitly. Note also that sometimes the final is mandatory, for example when using local classes:

In addition to accessing fields defined by the containing class, local classes can access any local variables, method parameters, or exception parameters that are in the scope of the local method definition and declared final.

On the other hand, there might be times when you do want to be able to reassign to a variable. Obviously in this case you should not declare it as final.


In programming it is best to get a compiler error than a logic error. Compiler errors are found in seconds and are corrected very fast.

final keyword can help to convert logic errors into compiler errors without too much effort.

For example:

public int test(int num){
   num = 10;
   x = num*2
   return  x;
}

In the example above we could accidentally assign a new value to num variable so the return value will be wrong. With final keyword we prevent this kind of errors.

public int test(final int num){
       num = 10; //compiler error
       x = num*2
       return  x;
    }


Immutable classes are inherently thread safe in which you can share safely across threads. If you declared all fields of a class final (and the class itself is final) also assuming each field itself is immutable, that object would be safe to share across threads.


Theoretically JVM can optimize those better, but I don't know if it really does. final is used to indicate that you can assign a value to the variable only once.


And practically the object is in 2 or even more classloaders like app server environment and therefore will get assigned more than once even final. Or load a declared final from a properties file later changed, happened here removing declared final to normal variables got more pragmatic.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜