Why would you declare getters and setters method private?

Vandan Patel picture Vandan Patel · Jan 24, 2012 · Viewed 16.2k times · Source

I saw a code where getters and setters methods are declared private. I am trying to figure out the logic behind it, and I am really having hard time to understand why would you declare them as private? That's exactly opposite of what we are trying to achieve through getters and setters.

Answer

Luchian Grigore picture Luchian Grigore · Jan 24, 2012

I can think of several reasons:

  • you want to prevent future public access.

If a different programmer sees your code and wants access to a variable, but there are no setters and getters, he might think you just forgot about them, and add them themselves. However, if you declare them as private, it's a statement of intent, saying I don't want these variables to be changed or accessed from the outside.

  • you want to associate setting and getting with other actions

Say you don't want public accessors. But maybe you want a count of how many times a private variable is changed. It's easier to use a setter rather than incrementing the count every time you access that variable.

  • you want a central access point

Again, you don't want public access, but during debugging, you might want to put a breakpoint in every place a private member is changed. So instead of setting breakpoints everywhere in the class, you just set one in the accessor.