简体   繁体   中英

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

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.

If your class is going to be used in the environment where setter is not required (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM