通常,在我自己的项目中,我使用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有什么好处吗?
发布评论