-1

I have been in a small argument about the reason to create "getters" inside a class to get the value of a variable inside the class which will be created as an object in our case.

public class big {

  public static void main(String[] args) {
    obj me = new obj();
    int size;
    size = me.size;

    //OR

    size = me.getsize();
  }
}

this is the main class

and i have made 2 methods of getting the "size" of the object

public class obj {
  public static int size = 10;

  public static int getsize() {
    return size;
  }
}

i have done some testing and calling the function seems oddly faster by around 100 nanoseconds. why so?

thegauravmahawar
  • 2,802
  • 3
  • 14
  • 23
  • 5
    Possible duplicate of [Why use getters and setters?](http://stackoverflow.com/questions/1568091/why-use-getters-and-setters) – YoungHobbit Oct 12 '15 at 08:19
  • 1
    Are you aware that you are using `static` with you method and variable and understand about how `static` works differently than non-static stuff? – Abubakkar Oct 12 '15 at 08:19
  • When doing this kind of speed measurements it's best to use a tool like http://nitschinger.at/Using-JMH-for-Java-Microbenchmarking. – Simon Oct 12 '15 at 08:19
  • See also Effective Java 2nd Ed Item 14: "In public classes, use accessor methods, not public fields" – Andy Turner Oct 12 '15 at 08:21
  • If your question is about the difference in speed, you need to show what kind of testing you did for measuring it. So add that to your question. Better check if your test is a [good benchmark](http://stackoverflow.com/q/504103/4125191). – RealSkeptic Oct 12 '15 at 08:36

1 Answers1

-1

The advantage lies in security. If you have direct access to members, you can change their values while that's not what you (as developer of the class) intend.

for instance:

public String myValue = "help";

here, anyone can do: MyClass.myValue = null;

while, if it is not public, but private:

public void setMyValue(String newVal){
  if ( newVal != null  }{ myValue = newVal; }
}

This way, you'll avoid NullPointerExceptions. You'll need a getter then, to get the value.

Stultuske
  • 9,296
  • 1
  • 25
  • 37
  • 1
    At least in Java that is only true for fields with a primitive data type. Every instance will be returned as reference, unless you explicitly make sure that your getter always returns a clone, never the actual instance. That in turn requires you to always call the setter, if you want to change anything in an instance that is kept within another object. – Till Helge Oct 12 '15 at 08:21
  • 2
    The question is "i have done some testing and calling the function seems oddly faster by around 100 nanoseconds. why so?". And your answer is "The advantage lies in security...." – Erwan C. Oct 12 '15 at 08:22