Question

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))?

Was it helpful?

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.

OTHER TIPS

The final keyword has different meanings when used on methods and on method parameters.

  • When on a method, it means this method cannot be overriden.
  • When on a method parameter, it means the method cannot
    change this parameter's value in its body.

EDIT:

In some cases, the compiler forces you to declare them final. Here is one such example (this is some typical DAO code). So people usually do it only when the compiler forces them to do it.

public List<Process> getProcesses(final Integer uid, final String status) {
    return getHibernateTemplate().executeFind(new HibernateCallback() {
        public Object doInHibernate(Session session) 
                throws HibernateException, SQLException 
        {
            StringBuilder sbQuery = new StringBuilder
            ("select * from [process] where [uid] = :u and [status] = :s");

            SQLQuery query = session.createSQLQuery(sbQuery.toString());

            query.addEntity(Process.class);

            query.setParameter("u", uid);
            query.setParameter("s", status);

            List l = query.list();
            return (List<Process>)l;
        }
    });
}

Yes, it is. The Eclipse IDE has code clean up settings that will do this for you automatically, although I only use it for method parameters.

You should be careful while using final keyword in java

1.Applying final keyword to variables in which we cannot reassign the value to thet variable

2.If a method decared as final that method cannot overridden

3.If class declared as final that cannot be extends(key benifit of inheritance will be lossed)

   What i can say is Think before using `final` keyword

Declaring a method parameter as final has the following implications :

  • The method cannot change the method parameter to point to another reference.
  • The method CAN modify the method parameter i.e change the state of the object being referred by the parameter (modify instance variables)

I will illustrate this with the following example. Assume I have a Class to represent an employee :

class Employee
{
    public String name;
    public Integer id;
}

Case 1 :

  public void test(final Employee emp)
  {
       emp = new Employee(); //Invalid since you are changing the reference
  }

Case 2 :

   public void test(final Employee emp)
   {
       emp.name = "John Doe"; //Valid
   }

This is different from a const parameter in C++ which also stops the method from making any changes to the state of the object/reference being passed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top