Java惯例:使用getter / setter WITHIN类?

编程入门 行业动态 更新时间:2024-10-25 11:23:14
本文介绍了Java惯例:使用getter / setter WITHIN类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我的教授真的强调通过总是使用访问器和mutator来访问私有实例变量来防止隐私泄漏;

My professor really emphasizes protecting against privacy leaks by always using accessors and mutators to access private instance variables; however, do I have to use the getters/setters of a class within the class?

例如,如果我有以下类:

So for instance, if I have the following class:

public class Person { private String name; private int age; }

,我想为它写一个toString我可以写:

and I want to write a toString() method for it. Can I just write:

public String toString() { return name + " " + age; }

或者我需要这样做:

public String toString() { return this.getName() + " " + this.getAge(); }

推荐答案

但是,您的教授可能会喜欢使用方法,而不是直接访问。这是为什么。

You CAN do either one. However, your professor might appreciate using the methods instead of the direct access. Here's why.

假设你有这样的类:

class SomeClass { private int someValue; private String someString; public SomeClass(int someValue, String someString) { this.someValue = someValue; this.someString = someString; } public int someValue() { return someValue; } public int someString() { return someString; } public String toString() { return someValue + ": " + someString; } }

这很简单,对吧?那么,如果突然我们想改变我们如何计算 someValue 的实现,并基于 someString :

It's pretty straightforward, right? Well, what if all of a sudden we want to CHANGE the implementation of how we calculate someValue, and base it off of someString:

public int someValue() { int value = 0; for(int i = 0; i < someString.length; i++) { if(someString.charAt(i) == ' ') value++; } return value; }

现在你还必须改变每个地方变量 someValue 。

Now you also have to change every place where variable someValue was used.

所以如果你想让代码更容易维护,使用方法调用。这样当你对你的代码进行编码(并相信我,它一直在变化),你只需要在一个地方而不是两个。

So if you want to make the code easier to maintain in the long run, use the methods calls. This way when you code changes on you (and trust me, it changes all the time) you only have to change it in one spot instead of two.

您将想要使用方法调用获取 someString ,而不是在最后一个方法中的直接访问: - )

And yes, you would want to use a method call in getting someString instead of the direct access in the last method :-)

更多推荐

Java惯例:使用getter / setter WITHIN类?

本文发布于:2023-05-27 09:58:23,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/285785.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!