What are the advantages of defining a private attribute instead of a public attribute? Why should I have the extra work of creating methods to access and modify privates attributes if I can just make them public?
A private attribute provides you a level of protection from the users of your class, for that attribute. If you use a public attribute, you will need to add in more logic to test for invalid values up front, which can be more work, as well as more computationally expensive.
Private. In the context of class, private means the attributes are only available for the members of the class not for the outside of the class.
In many object-oriented languages, certain attributes can be declared as private, making it impossible for users of a class to directly view or modify their values. The designer of the class then provides methods to control the ways in which these attributes can be manipulated.
Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other . dlls or even other applications.
In the short term there's none, other than making OOP purists unhappy.
(I'm assuming you mean exposing properties that would otherwise use getters/setters - obviously there's a big difference if you leave ALL your attributes public).
In the long-term there are a few really good reasons for doing it.
Firstly it allows you to validate input at its source instead of later having to back-track the origin with a combination of hardware breakpoints and black-magic.
E.g.
void Foo::setWeight(float weight)
{
ASSERTMSG(weight >= 0.0f && weight <= 1.0f, "Weights must fall in [0..1]");
mWeight = weight;
}
It also allows you to later change the behavior of your object without needing to refactor client code.
E.g.
void Foo::setSomething(float thing)
{
mThing = thing;
// 2009/4/2: turns out we need to recalc a few things when this changes..
...
}
If you use getters/setters you can perform logic upon changes or access. You could validate input, instead of assuming it is always correct. You could track how many times the value is fetched.
Most of all, it's good design. It gives you, the developer of the class, more control over how it is used and a greater ability to prevent misuse, abuse, or just someone doing something wrong.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With