Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a getter without a setter

Tags:

java

This might seem like a question already asked, but I couldn't find a question asked in this specific way. I don't understand how adding a setter improves upon this code. I know it's standard practice to add the setter, but I don't understand why.

public class DataHelper extends Activity {

    private final double cards = 52;

    public double getCards(){
        return cards;
    }
like image 850
seekingStillness Avatar asked Jan 30 '26 02:01

seekingStillness


1 Answers

Since cards is final, adding a setter here would be meaningless: this field cannot change.

If it wasn't final, but you didn't want to allow external modifications, then adding a setter would be pointless.

Only add a setter if it makes sense in your design to allow external modifications to a field.

As to the question of why add a setter instead of directly modifying a field, the answer would be encapsulation. By providing access only through methods, you can change the underlying implementation without affecting users.

A better example would be a Font class. A common feature of fonts is that the size can be in pixels or in points. If the internal representation is in points, and you expose that as a field, then later if you need to change the internal representation to pixels, you cannot, without affecting all current users. Instead, if you provide a setter, then you can freely change the internal representation without affecting anybody.

Providing methods instead of direct access to fields leaves the option open to modify the internals of the class later without affecting users. This is good encapsulation, information hiding.

like image 160
janos Avatar answered Jan 31 '26 17:01

janos