在类中为自己的字段使用getter / setter有什么好处吗? [英] Is there any benefit to using getters/setters inside a class for its own fields?

查看:109
本文介绍了在类中为自己的字段使用getter / setter有什么好处吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通常,在我自己的项目中,我使用getter和setter进行任何字段访问,然后我按照我的工作做同样的事情。前段时间,我们项目的技术主管问我为什么这样做,为什么这比仅使用字段本身更好(如果需要通过子类访问,可以选择声明它们受保护)。我无法得出一个明确的答案。

Usually, in my own projects I use getters and setters for any field access, and I followed to do the same on my job. Some time ago, the tech lead of our project asked me why I was doing that and why is this better than just using fields themselves (with an option of declaring them protected if they needed to be accessed by subclasses). I couldn't come up with a clear answer.

那么,是否有任何理由在类中使用getters和setter来获得类的自己的字段,或者它是否更好直接使用字段?

So, are there any reasons to using getters and setters inside a class for class' own fields, or is it better to use fields directly?

推荐答案

最明显的答案是副作用:

The most obvious answer is side effects:

int getCost()
{
    if (cost == null) {
        calculateCost();
    }

    return cost;
}

如果您需要费用,请使用 getCost() 。如果您想查看是否已计算成本,请使用费用

If you need the cost, use getCost(). If you want to see if cost has been calculated, use cost.

这篇关于在类中为自己的字段使用getter / setter有什么好处吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆