Abstraction and Encapsulation
Encapsulation is the act of protecting data integrity. A class is properly encapsulated when its internal data cannot possibly be set to an invalid or inconsistent state. This can be achieved by:
1) Information hiding: removes the class's internals from the eyes of its clients so that there is less risk of corrupting of corrupting those internals.
2) Bundling of data and operations: helps establish a single entry point for all actions to be done on this class. This way you can perform all required validation and integrity checks before modifying this class.
Each class has a number of invariants, these are conditions that must be true at all times.
It is the responsibility of the software developer that these invariants are never violated and the best way to do that is to encapsulate your classes so that this is never an option.
Example: the set method of the invariants are marked as private so only the class may set it. In this a course cannot be active if the number of students is zero. This helps to maintain data consistency.
Comments
Post a Comment