Encapsulation
Reading Only

Encapsulation creates a structure to bundle data and behavior. In turn, it also helps protect the integrity of the structure's internal state. A major part of encapsulation involves restricting access to data and behaviors, specifically called "Data Hiding".

When designing classes, remember that an object is not obligated to expose all of its methods and variables. Not every method and class variable must be marked with the public access modified. Instead, a "well-designed" object will only expose the variables and methods that other objects must interact with. Everything else should remain concealed and marked with the private access modifier.

When we want to invoke behavior from an object, we call one of its public methods. A class like this is a classic example of encapsulation:

public class ShoppingCart { private List<Item__c> items = new List<Item__c>(); public void addItem(Item__c item){ if(canBeAdded(item)){ items.add(item); } else { // show user an error message } } private Boolean canBeAdded(Item__c item){ // validation logic } public Decimal calculateTotalPrice(){ Decimal totalPrice = 0.0; for (Item__c item : items) { totalPrice += item.Price__c * item.Quantity__c; } totalPrice = applyDiscounts(totalPrice); totalPrice = applyTaxes(totalPrice); totalPrice = applyShippingFee(totalPrice); return totalPrice; } private Decimal applyDiscounts(Decimal totalPrice){ // Implementation } private Decimal applyTaxes(Decimal totalPrice){ // Implementation } private Decimal applyShippingFee(Decimal totalPrice){ // Implementation } }



We've used the private access modified for the items list and the various helper methods. This keeps the internal data and implementation details hidden from the external classes.

The public methods like addItem and calculateTotalPrice provide a well-defined interface for interacting with the ShoppingCart class. Anyone who wishes to use this class can add items and calculate the total price but doesn't need to know the specific implementation details.

There's also validation logic that's encapsulated. The canBeAdded method encapsulates the validation logic for adding items. This ensures the cart's state remains consistent and prevents invalid items from being added. If this validation logic is changed, the addItems method won't need to be modified either.

The calculateTotalPrice method encapsulates the complex logic for calculating the total price. It breaks down the calculation into smaller, private methods (applyDiscounts, applyTaxes, and applyShippingFee), which makes the code more maintainable and easier to understand.

The ShoppingCart class demonstrates encapsulation principles by keeping the internal data and implementation details hidden, providing a straightforward and user-friendly public interface, encapsulating validation and complex calculations, and promoting modularity and reusability.