简体   繁体   English

使用没有setter的getter

[英]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. 我不明白添加setter如何改进此代码。 I know it's standard practice to add the setter, but I don't understand why. 我知道添加setter是标准做法,但我不明白为什么。

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. 由于cardsfinal ,在这里添加一个setter是没有意义的:这个字段不能改变。

If it wasn't final , but you didn't want to allow external modifications, then adding a setter would be pointless. 如果它不是final ,但你不想允许外部修改,那么添加setter将毫无意义。

Only add a setter if it makes sense in your design to allow external modifications to a field. 如果在您的设计中有意义,则只需添加一个setter,以允许对字段进行外部修改。

As to the question of why add a setter instead of directly modifying a field, the answer would be encapsulation. 至于为什么添加一个setter而不是直接修改一个字段的问题,答案就是封装。 By providing access only through methods, you can change the underlying implementation without affecting users. 通过仅通过方法提供访问权限,您可以在不影响用户的情况下更改基础实现。

A better example would be a Font class. 一个更好的例子是Font类。 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. 相反,如果您提供了一个setter,那么您可以自由地更改内部表示而不会影响任何人。

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. 如果您的类将在不需要setter的环境中使用(例如ORM /依赖注入/序列化框架),那么不使用setter就可以了。 In this particular case setter does not make much sense since variable is final and set only once. 在这种特殊情况下,setter没有多大意义,因为变量是final,只设置一次。 So, getting value of the private variable using cards method is not a bad idea. 因此,使用卡片方法获取私有变量的值并不是一个坏主意。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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