Skip to content Skip to sidebar Skip to footer

Is Having A Lot Of Getters & Setters A Good Idea?

When writing an application(in java) that you intend to open source, is it generally a good idea to have a lot of getters & setters and make variables private? More specificall

Solution 1:

If you are discussing getters & setters in ANDROID, check what android documentation tell:- Avoid Internal Getters/Setters On Android, this is a bad idea. Virtual method calls are expensive, much more so than instance field lookups. It's reasonable to follow common object-oriented programming practices and have getters and setters in the public interface, but within a class you should always access fields directly.

Solution 2:

if all the private variables are expected to be accessed from out side then yes.

Suppose you have certain flags those aren't going to be used from outside then no need of getters/setters for those.

Also See

Solution 3:

Lets put it this way, you don't feel any need of having getters/setters and you plan to make your properties non-private. It doesn't appear to be any problem with this approach. But you must ask few questions to yourself.

  • Are you having any property whose value should undergo some checking before assignment? (Need for a setter)
  • Do you have any mutable property which you don't want to expose as it is? (Need for a getter)

Now, if you think your few properties need getters/setters, but not all. Then I would say create getter/setter for all of them for the sake of consistency. :)

Further see, Effective Java 2nd Edition,

  • Item 13: Minimize the accessibility of classes and members
  • Item 14: In public classes, use accessor methods, not public fields
  • Item 15: Minimize mutability
  • Item 38: Check parameters for validity
  • Item 56: Adhere to generally accepted naming conventions

Post a Comment for "Is Having A Lot Of Getters & Setters A Good Idea?"