Encapsulation hides internal state and ensures invariants are maintained.
Encapsulation allows you to control access to an object's internal state by using private fields and public methods. This ensures that invariants, or rules that must always hold true, are maintained consistently. For example, in a Product class, setting the price should only be done through a dedicated method that checks if the price is positive, preventing invalid states.
Additional Notes
Why is encapsulation crucial for maintaining object invariants?