Search code examples
javac++final

Using final parameter correctly in Java


In C++, as much as I know, it is a good practice to add const parameter to these variables which are not going to change and to these methods, which return values, for example:

bool ExpenseManager::checkCategory(const string &userName, const string &categName) const{}

My question: is it a good practice to use final in Java just like const in c++ and declare specific methods and/or variables final (like for values which are passed for constructor (public Something(final String haha))?


Solution

  • Note that declaring a parameter final in Java is an implementation detail while a const parameter in C/C++ changes the method signature! final only means that the variable will not change. Any object referenced by the variable CAN change. So, final means NOTHING for the caller of the method. In contrast a const parameter defines a contract with the caller: The method promises that it will not alter any data handed in via the parameter. With java, you cannot create such a contract so you must fall back to immutable objects or defensive copies.

    So to get back to your question: Since final is an implementation detail, it does not matter when considering interfaces. It is rather a matter of taste. Some people, especially those coming from a functional language love final, since they state that a variable should only be mutable when it is actually mutated somewhere. Others simply don't like the added keyword which adds visual noise.

    Usually, this decision is made on a project level: Either use final everywhere in the project or nowhere. Every developer on the project should do the same thing or the code will look inconsistent.