I understand that only the class can access the data so therefore it is “safer” and what not but I don’t really understand why it is such a big deal. Maybe it is because I haven’t made any programs complex enough where data could accidentally be changed but it just a bit confusing when learning classes and being told that making things private is important because it is “safer” when the only time I have changed data in a program is when I have explicitly meant to. Could anyone provide some examples where data would have been unintentionally changed had that data not been private?
Share
Depends what you mean by “unintentional changes”. All code is written by someone so if he is changing a member variable of a class then the change is intentional (at least from his side). However the implementor of the class might not have expected this and it can break the functionality.
Imagine a very simple stack:
Now
CurrentItemIndexpoints to the index which represents the current item on top of the stack. If someone goes ahead and changes it then your stack is corrupted. Similarly someone can just write stuff intoItems. If something ispublicthen it is usually a sign that it is intended for public usage.Also making members private provides encapsulation of the implementation details. Imagine someone iterates over stack on the above implementation by examining
Items. Then it will break all code if the implementation of the stack gets changed to be a linked list to allow arbitrary number of items. In the end the maintenance will kill you.The public interface of a class should always be as stable as possible because that’s what people will be using. You do not want to touch x lines of code using a class just because you changed some little detail.