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();
}
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:
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 ofsomeString:Now you also have to change every place where variable
someValuewas 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
someStringinstead of the direct access in the last method 🙂