简体   繁体   English

使用getter或direct名称在自己的类中获取私有变量?

[英]Get private variable within its own class with getter or direct with name?

whats the more prefered way to get private variables within the same Class. 什么是在同一个类中获取私有变量的更优选方式。

for instance we have this code: 例如,我们有这个代码:

public Class TestClass
{
    private String name;

    public String getName()
    {
        return name;
    }
    public void setName(String name)
    {
        this.name = name;
    }

... ...

    public String someMethod()
    {
        return getInfo(name);
        or
        return getInfo(getName());
    }
}

... ...

so whats the prefered way, to get the private variable within the same class with its name or with its getter ? 那么最好的方法是,将私有变量与其名称或其getter一起放在同一个类中?

Update: The getter will always just return name. 更新:getter将始终只返回名称。

Well, this I think is a preference/situation related question. 嗯,我认为这是一个偏好/情况相关的问题。 If you call directly the field you will get a better time because you don't do an additional method call which are very fast anyway, and maybe be a little more concise. 如果你直接打电话给你,你会得到一个更好的时间,因为你不进行额外的方法调用,无论如何都要快,也许更简洁。 But if you use a getter you can add another layer of abstraction, and do some other stuff in there, like returning another value instead of the default is the field is not set, something like: 但是如果你使用getter你可以添加另一层抽象,并在那里做一些其他的东西,比如返回另一个值而不是默认值是没有设置字段,例如:

int getAge() {
   return (age < 18) ? 18 : age;
}

Also this will help in the case of objects to avoid to return null, like: 这也有助于避免返回null的对象,例如:

Stuff getStuff() {
    if(stuff == null) {
        return Stuff.NULL_OBJECT;
    }
}

Please beware that Stuff is my class and the NULL_OBJECT field is a Null object pattern implementation, and my example doesn't have any synchronization. 请注意,Stuff是我的类,NULL_OBJECT字段是Null对象模式实现,我的示例没有任何同步。

This being said, I always use the direct field access approach if the situation doesn't require something extravagant. 话虽如此,如果情况不需要奢侈的话,我总是使用直接现场访问方法。

Preference will depend on context. 偏好取决于背景。 In your case above where the getter simply returns the variable, many developers will tend to return the variable directly. 在上面的例子中,getter只返回变量,许多开发人员倾向于直接返回变量。 However, if your getter is more complicated or believe it might change in the future, then the use of the getter might be preferred. 但是,如果你的getter更复杂或者相信它将来会发生变化,那么可能更喜欢使用getter。 It all depends on what name represents, what getName() returns and what getInfo(...) expects. 这完全取决于name代表什么, getName()返回以及getInfo(...)期望的内容。

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

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