Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, is it ever a bad idea to make an object's members publicly available?

I have a data class in my application. My application will never be used as a public API and I will be the only person developing code within my project.

I am trying to save every ounce of processor and memory power I can.

Is it a bad idea to make my data members in my data class to have public/protected/default protection so that I don't have to use a getter? Using a getter would require slightly more memory and creation of a stack and such...which I believe isn't necessary. The only reason I can see in using a getter is for protection/privacy, but if I'm the only coder and nobody else is going to be using my API, then is it a bad idea not to use the getters?

Please let me know if this is stupid.

like image 520
jbu Avatar asked Feb 16 '09 22:02

jbu


3 Answers

If you are replacing getters/setters for performance/memory optimisation, then you are taking the wrong approach. These are almost certainly not going to be the reason your application runs slowly or uses too much memory.

The cardinal sin of optimisation is to do it before you know that you need to. Optimise only when you have real information showing you where the most time/memory is being wasted, and then spend your time optimising that. The thinking behind this is that you will gain more by shaving off 5% of time in a piece of code that takes up 80% of the total run time, than shaving off even 20% in a piece of code that contributes only 5% to the total run time. (Same applies to memory).

Also, I would be careful about designing the application as you suggest, since it will mean that some properties (eg: simple properties) will be directly accessible, while others (more complex derived properties, or properties where you do not want to expose the underlying types) will have getters/setters. So you will end up with a mix of access styles, which will be less maintainable.

like image 73
KarstenF Avatar answered Nov 10 '22 17:11

KarstenF


It is a bad idea to make members publicly available as an optimization. As others have said, it will have virtually no impact. However, if the object is a simple data structure with little behavior, it's fine to write it that way. As long as you're doing it for simplicity and readability, not performance.

like image 36
Craig P. Motlin Avatar answered Nov 10 '22 16:11

Craig P. Motlin


Chances are good that trivial getters and setters will be inlined anyway - but with public fields you'll have lost the distinction between contract (API) and implementation. Even if this is only an API that you will use, it's good to keep things loosely coupled IMO.

like image 45
Jon Skeet Avatar answered Nov 10 '22 17:11

Jon Skeet