Why would you declare getters and setters method private? [duplicate]

限于喜欢 提交于 2019-11-29 01:09:49

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.

That's exactly opposite of what we are trying to achieve through getters and setters.

Actually, it is not. The reason for declaring getters and setters is to hide the fields. This is done to avoid unwanted coupling; i.e. clients of an API depending on the implementation details of the API. (That coupling can be problematic for a number of reasons.)

The reason for making the getters and setters private is to make the corresponding part of the object's abstract state private. That's largely independent of the decision to use getters and setters or not.

While the case for using getters and setters is not as strong for private state, there are still tangible benefits. For instance:

  • The getter/setter methods provide a place for adding extra behavior or error checking code.

  • They also provide a place for adding debug code or injecting test code (for unit testing).

  • Getters and setters can be overridden. You can't do that with fields (private or not).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!