In computer programming, an accessor method is a method that fetches private data that is stored within an object. An accessor provides the means by which to obtain the state of an object from other program parts.
An Accessor method is commonly known as a get method or simply a getter. A property of the object is returned by the accessor method. They are declared as public.
In Java, accessor methods return the value of a private variable. This gives other classes access to that value stored in that variable. without having direct access to the variable itself. Accessor methods take no parameters and have a return type that matches the type of the variable they are accessing.
In computer science, a mutator method is a method used to control changes to a variable. They are also widely known as setter methods. Often a setter is accompanied by a getter (together also known as accessors), which returns the value of the private member variable.
Often, I come across code where the Getter method is repeatedly used/abused to get some value or pass it as a method parameter, for ex:
public class Test {
public void someMethod() {
if(person.getName() != null && person.getName().equalsIgnoreCase("Einstein")) {
method1(person.getName());
}
method2(person.getName());
method3(person.getName());
method4(person.getName());
}
}
I usually code it, as below:
public class Test {
public void someMethod() {
String name = person.getName();
if(name != null && name.equalsIgnoreCase("Einstein")) {
method1(name);
}
method2(name);
method3(name);
method4(name);
}
In my opinion, there is considerable memory/performance advantage in assigning the getter to a variable and using it, as Getters are Java methods and use stack frames. Is there really a considerable advantage in coding that way? }
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