Michał Tabor
Michał Tabor

Reputation: 2467

Should I use public or package access? Why should I use private for fields?

So 2 questions:

  1. Should I use for my classes public or package access? In every project all my classes are kept in one package and I never use any methods from them in other projects. So do I need public access? I think package would be ok for me. And would be safer.
  2. I know habit of making fields private and making getters and setters for them. I also understand idea of hermetic, however everywhere I read about philosophy of making getters and setters I get only one reason: "You must do getters or setters so you are sure that one variable is not directly used in other part of program. Thanks to this you can be sure that you can make in such getter changes (like if statement which decides what value return) and be sure that every part will behave like that". But in 99.9% getters just return class private value. Almost every time getter have just 1 line "return XXX". So are there any other possiblites of using getters? And setters? I once deleted getters and setters from my project, made fields public and what I got was that my project got almost 30% smaller.

Upvotes: 0

Views: 166

Answers (1)

tdlrali
tdlrali

Reputation: 78

It's generally a good idea to make all fields private, and to implement getters and setters as needed. That way, you can make sure that the fields aren't used/changed in a way that is unintended. For example, you can add error checking code to your setters, to make sure fields aren't set to values that will break other things. If other classes can set the field directly, you can't prevent that.

If you have a good reason to make a field with package visibility, or public, then of course you can do so, but you have to be aware of what problems that can cause if other people/classes use your fields the wrong way.

It probably doesn't make a lot of difference in your small project, because you know not to set fields to the wrong values, or screw up otherwise - but if other people use your classes or your project grows in size, you will appreciate the fact that the actual fields are private and you can control access via the getters/setters.

Upvotes: 1

Related Questions