How far should I go to avoid internal getters/setters within a class

146 views Asked by At

I have more of a "how much is too much" question. I have a Java class that defines several getters/setters for use by external classes (about 30 altogether). However, the Java class itself requires the use of these variables as well in some cases.

I understand the concept of using member fields instead of the getter methods within a class, but the getters in this case perform a function (unmasking an integer to be specific) to create the value to be returned.

So from a performance and memory reduction perspective, for the few calls within the class that need those values, I'm curious if I should...

a. Just call the getter

b. Do the unmasking wherever I need the values throughout the class, just like the getter

c. Create variables to hold those values, load these up by calling all the getters on startup, and use those within the class (30 or so integers may not be a serious memory risk, but I would also need to add to my code to keep those updated if a user sets new values...since the value is updated and masked).

Any thoughts are appreciated!

3

There are 3 answers

2
Zulan On BEST ANSWER

a) Call the getter - as you pointed out it's the right and clean way in your case.

b) and c) would be premature optimization and most likely do more harm than good (unless you REALLY know that this particular spot will be a hot spot in your code AND your JIT-compiler will not be able to optimize it for you).

If you really hit performance problems at some point, then profile the application and optimize only hot spots manually.

2
rlb.usa On

A. Just call the getter.

From a performance and memory reduction perspective, there is really little to no impact here on constantly re-using the same functions. That's what code reuse is all about.

From a high level execution/performance view, we do something like this:

code: myGetter()
program : push the program state (very few cycles)
program : jump to mygetter (1 clock cycle)
program : execute mygetter (don't know your code but probably very few cycles)
program : save the result ( 1 clock cycle)
program : pop the program state ( very few cycles )
program : continue to next line of code ( 1 clock cycle)

In performance, the golden rule of thumb is to spend your time optimizing what really makes a difference. For all general purposes, disk I/O takes up the most time and resources.

Hope this helps!

1
Karl Bielefeldt On

Don't Repeat Yourself is the guiding principle here. Trying to save a function call by repeating the same unmasking code throughout a class is a recipe for disaster. I would just call the getter within the class.