Show in graph

Software → Software Design

Encapsulation

The practice of keeping data and behavior together while controlling access to internal details.

Brief explanation

Encapsulation means keeping an object’s internal state and rules inside the object. Other code should ask the object to perform meaningful operations instead of directly changing its fields and accidentally bypassing business rules.

Code example
Bad example
Python
class Order:  def __init__(self):      self.items = []      self.status = "draft"class OrderService:  def checkout(self, order: Order) -> None:      order.items.append({"name": "Book", "price": -10})      order.status = "paid"
Good example
Python
class Order:  def __init__(self):      self._items: list[dict[str, float | str]] = []      self._status = "draft"  def add_item(self, name: str, price: float) -> None:      if price <= 0:          raise ValueError("Price must be positive")      self._items.append({"name": name, "price": price})  def mark_paid(self) -> None:      if not self._items:          raise ValueError("Cannot pay for an empty order")      self._status = "paid"class OrderService:  def checkout(self, order: Order) -> None:      order.add_item("Book", 10)      order.mark_paid()