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.createPart(
"/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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With