Global access to variables is dangerous because you don’t have strict control over who has access to the global variable, or how they use it.
Only the public members of a
Type suffers from the same problem, but just on a smaller scale.
Encapsulation allows the programmer of a
Type to:
- Actively control the access to its internals (pointers, variables, ...), by: none / read only / write only / read & write.
- Secure operations, by denying certain destructive user actions (like pointer overwriting, deallocating, ...)
With a fully encapsulated
Type, you only need to know what member procedures are publicly available to use the
Type, what arguments they take, and what values they return. It doesn’t matter how the
Type was implemented internally.
For example, a
Type holding a list of names could have been implemented using different data structures.
In order to use the
Type, you don’t need to know (or care) which.
This dramatically reduces the complexity of your programs, and also reduces mistakes.
Hiding the internal implementation details:
- internal members declared as Private/Protected and user interface using methods and properties as getter/setter,
- in addition to define constructors, copy-constructor, destructor, assignment operators, ... ,
provides some abstraction.
More than any other reason, this is the key advantage of encapsulation.