Question

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.

Was it helpful?

Solution

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.

OTHER TIPS

The practise I know is that you may use public static final fields with immutable types, like System.out for instance. I do add getters to instance fields, however.

I agree with you though that there is barely harm exposing a final String. Beware of mutable types, though. Furthermore, since there's inlining and code generation in the IDE the costs of the getters tend to be rather litte, both writing code and at runtime.

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