Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getters for final variables

Tags:

java

oop

getter

Right now I am creating a load of classes that will hold my configuration and that is it. All I do is store the values from the configuration file.

More than half the code is the getters and I am wondering whether the practice is still to have the getters or just access the variables directly.

So this:

public myClass
{
    public myClass(String name)
    {
        this.name = name;
    }

    final String name;

    public final String getName()
    {
        return name;
    }
}

Or:

public myClass
{
    public myClass(String name)
    {
        this.name = name;
    }

    public final String name;
}

It seems really silly to have all the getters there when they are not actually doing anything but return the variable. But I have been told that it is common Java practice to have the getter in there anyways.

like image 721
Cheetah Avatar asked Jul 15 '13 16:07

Cheetah


1 Answers

Encapsulating the data with getters can provide several advantages, including:

  • You can change the field to some other representation, without affecting callers.
  • You can add additional code in the getter.
  • You can implement an interface that provides the getters.
  • You can provide read-only access to the fields even if they weren't final.
like image 138
Andy Thomas Avatar answered Oct 12 '22 23:10

Andy Thomas