Java惯例:使用getter / setter WITHIN类? [英] Java Conventions: use getters/setters WITHIN the class?

查看:195
本文介绍了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类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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