Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Immutable Type: public final fields vs. getter

I need a small Container-Class for storing some Strings which should be immutable. As String itself is an immutable type, I thought of something like that:

public final class Immu {   public final String foo;   public final String bar;    public Immu(final String foo, final String bar)   {     this.foo = foo;     this.bar = bar;   } } 

Many people seem to object using public fields at all and use Getters instead. IMHO this would be just boilerplate in this case, because String itself is immutable.

Other thoughts I may be missing on this one?

like image 601
Daniel Avatar asked Aug 03 '11 14:08

Daniel


People also ask

Should getters be public or private?

In general, they should be public. If they are private they can only be called from within your class and, since you already have access to the private variables within your class, are redundant. The point of them is to allow access to these variables to other, outside, objects.

Should getters and setters be public or private?

Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.

Should getters and setters be final?

It makes sense to make a getter final if the POJO aimed to be immutable. final modifier will disable sub classes to override that method. You should only use it if you want this design, but it depends.

Can final variables be public?

A public static final variable is a compile-time constant, but a public final is just a final variable, i.e. you cannot reassign value to it but it's not a compile-time constant. This may look puzzling, but the actual difference allows how the compiler treats those two variables.


2 Answers

I would do what you believe is simplest and clearest. If you have a data value class which is only used by a restricted number of classes. esp a package local class. then I would avoid getter/setters and use package local or public fields.

If you have a class which you expect other modules/developers to use, following a getter/setter model may be a safer approach in the long run.

like image 81
Peter Lawrey Avatar answered Sep 18 '22 16:09

Peter Lawrey


The problem is the uniform access principle. You may later need to modify foo so that it's obtained through a method instead of being fixed, and if you exposed the field instead of a getter, you'll need to break your API.

like image 29
Daniel C. Sobral Avatar answered Sep 20 '22 16:09

Daniel C. Sobral