seekingStillness
seekingStillness

Reputation: 5093

Using a getter without a setter

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;
    }

Upvotes: 2

Views: 6602

Answers (2)

janos
janos

Reputation: 124648

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.

Upvotes: 9

Evgeny Semionov
Evgeny Semionov

Reputation: 323

If your class is going to be used in the environment where setter is not required (e.g. ORM / dependency injection / serialization frameworks), it should be OK to do not use setter. In this particular case setter does not make much sense since variable is final and set only once. So, getting value of the private variable using cards method is not a bad idea.

Upvotes: 4

Related Questions