Getters for final variables

Now I am creating a loading of classes that will contain my configuration, and that’s all. All I do is save the values ​​from the configuration file.

More than half of the code is getters, and I wonder if the practitioner still has getters or just access to the variables directly.

So this is:

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 stupid to have all the getters there when they actually do nothing but return a variable. But I was told that the usual practice of Java is that the recipient still has it.

+6
source share
2 answers

Encapsulating data using getters can provide several benefits, including:

  • You can change the field to another view without affecting callers.
  • You can add additional code to getter.
  • You can implement an interface that provides getters.
  • You can provide read-only access to fields, even if they were not final .
+11
source

The practice that I know is that you can use public static end fields with immutable types, like System.out . However, I am adding getters to the instance fields.

I agree with you that it is hardly possible to harm the final String . Beware of volatile types. In addition, since codes are embedded and generated in the IDE, the cost of getters is generally quite scarce, both for writing code and at runtime.

0
source

Source: https://habr.com/ru/post/949480/


All Articles