Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
407 views
in Technique[技术] by (71.8m points)

coding style - Java Conventions: use getters/setters WITHIN the class?

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;
}

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

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

OR do I need to do something like this:

public String toString()
{
    return this.getName() + " " + this.getAge();
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Let's say you have a class like this:

class SomeClass {
    private int someValue;
    private String someString;

    public SomeClass(int someValue, String someString) {
        this.someValue = someValue;
        this.someString = someString;
    }

    public int someValue() {
        return this.someValue;
    }

    public String someString() {
        return this.someString;
    }

    public String toString() {
        return 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;
}

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.

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...