In classes, variables are often made private for encapsulation, and to limit the variables to a certain scope allow better error control and fewer bugs. This makes sense, as the fewer places a variable can be accessed the fewer places a bug can occur with that variable.
However, I always see variables made private, and then a getter and setter function used to retrieve that value (sometimes even a pointer to that variable!). For example int a
is private to prevent public access, but then getA()
and setA()
allow direct access to them.
So don't getter functions and setter functions defy the point of it being private? I mean private variables with accessor function are the same as public variables, only the code to access them changes. (object.variable vs object.getVariable())
Is there a reason people make variables private with accessor functions? Are there any advantages when compared to making it public?
I am talking about programming in general, but mostly in C languages (i.e. C, C++, C#, Obj-C).
The key word and tag here is "encapsulation". You're hiding the details of a
, while still making it usable. I like the reasons already listed, there are many more. Here's another, you're debugging, and you find a
has an incorrect value. If a
is public, you'd have to check every place a
is accessed. If a
is private with a setter method, you know the only place a
could have changed is in a call to setA()
- would be a great place to put a breakpoint ;)