Consider the following class:
public class Person
{
private Integer age;
// Standard Accessors
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAgeAsTextString()
{
if (this.age == 20)
{
return "Twenty";
}
return "Unknown";
}
}
I just have 1 Integer, and 2 accessors. If I want to create a utility method that returns the objects' state as a String, is it best practice to refer to the class variable as this.age
, or should I be using getAge()
?
Is there a best practice or is it down to developer discression?
What's the importance of accessor methods? In a nutshell, an accessor method controls access to its attribute by providing a single location to inspect and/or modify that attribute. Code can also be added to perform operations such as range checks.
Accessor Method: This method is used to access the state of the object i.e, the data hidden in the object can be accessed from this method. However, this method cannot change the state of the object, it can only access the data hidden. We can name these methods with the word get.
Accessors and mutators are public member functions in a class that get (accessors) and set (mutators) the values of class member functions. In other words, these are functions that exist solely to set or get the value of a class member variable.
Yes, the methods of your class should call the getters and setters. The whole point in writing getters and setters is future proofing. You could make every property a field and directly expose the data to the users of the class.
I'd say its down to developer discretion.
I slightly prefer using the getter method. And if you have a class hierarchy, it's good to expose internal state via protected getters.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With