Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are getters required when the field vars are final?

in Java it's convention (as far as I am concerned) to keep your field variables private and access them using getters and/or setters. This is so that you can set rules for changing the values of the variables.

But what if the variables are final? Example:

public class Test {

    public final int MY_INT;

    public Test(int myInt) {
        MY_INT = myInt;
    }

}

Would this be allowed? It is compiled and works fine, but is it considered good code?

like image 765
Ludwig Avatar asked Dec 26 '14 18:12

Ludwig


2 Answers

This compiles but it's not considered good code.

MY_INT violates the naming convention: names with all caps are used for static final variables, also known as "class constants" (see this and this, Google's Java style guide too). to conform to naming conventions, it would be better to rename to myInt.

It's recommended to provide a getter to hide implementation details of your class. Interfaces contain only methods, not fields. If you let other classes refer to this field by name, then you lose the freedom to change the name or your internal representation later.

But most importantly, sub-classes cannot override fields, they can only override methods. If you provide a getter instead of a field, sub-classes will be able to override that and implement different behavior. So it would be better to provide a getter and forbid direct access to the field itself.

(Thanks to @Sotirios Delimanolis for the coding style guide links, much appreciated!)

like image 55
janos Avatar answered Oct 14 '22 00:10

janos


The provider answers are incomplete (even the one selected as "the answer"). Consider what would happen if the field in question was a Collection or an array of objects. It is a good practice to make ALL fields private and provide "getters" for these fields. But more specifically, your getter should return a (immutable) reference to the field (i.e. String), OR a defensive copy of mutable fields (i.e. array of objects). This is because, even if you cannot change the base address of the object in question, you can change the internals of the object (array or collection) by simply getting the base address. Keep in mind that by mutable fields I do not mean arrays or collections only. It applies to ANY mutable class.

Going back to the question, are getters REQUIRED? The answer is no. HOWEVER, if you want to have robust code, it is on your best interest to follow these best practices; even if it is just to create good habits. Unless you practice them regularly, you will not follow good practices when you code (and most likely others in your project won't either).

like image 28
hfontanez Avatar answered Oct 14 '22 01:10

hfontanez