Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessor Method Performance and Optimization

Tags:

People also ask

What is the purpose of accessor method?

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.

Which method is called as accessor method?

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.

What is the role of accessor methods in a class?

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.

Is accessor setter method?

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