Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it best practice to always use accessor methods, even when accessing local state?

Tags:

java

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?

like image 765
Jimmy Avatar asked Dec 03 '10 15:12

Jimmy


People also ask

Why is an accessor method necessary?

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.

What are the uses of accessor methods?

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.

Why do we need accessor and mutator?

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.

Should I use getters and setters inside the class?

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.


1 Answers

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.

like image 68
Bozho Avatar answered Oct 11 '22 07:10

Bozho