
from dataclasses import dataclass
# entity: one line of the order; a line without goods
# in it simply does not exist. eq=False, because an
# entity is equal only to itself, never by its fields
@dataclass(frozen=True, eq=False)
class OrderLine:
sku: str
price: int
count: int
def __post_init__(self):
if self.count <= 0:
raise ValueError("bad count")
@property
def cost(self) -> int:
return self.price * self.count
# entity: the order keeps its own rules and knows
# nothing about a database or a screen
class Order:
def __init__(self, id: int):
self.id = id
self._lines: list[OrderLine] = []
self._paid = False
@property
def lines(self) -> tuple[OrderLine, ...]:
return tuple(self._lines)
def add(self, sku: str, price: int, count: int):
# business rule: a paid order is closed
if self._paid:
raise RuntimeError("order is paid")
self._lines.append(OrderLine(sku, price, count))
@property
def total(self) -> int:
return sum(line.cost for line in self._lines)
# business rule: 10% off from 200
@property
def discount(self) -> int:
if self.total < 200:
return 0
return self.total // 10
@property
def payable(self) -> int:
return self.total - self.discount
@property
def paid(self) -> bool:
return self._paid
# business rule: an empty order is never paid
def pay(self):
if not self._lines:
raise RuntimeError("empty order")
self._paid = True
# client code
order = Order(1001)
order.add("pen", 30, 2)
order.add("lamp", 190, 1)
print("order", order.id)
print("lines", len(order.lines))
print("total", order.total)
print("discount", order.discount)
print("payable", order.payable)
order.pay()
print("paid", order.paid)
# every refusal comes from the rules themselves:
# no storage and no screen took part in them
try:
order.add("pen", 30, 1)
except RuntimeError as error:
print("refused:", error)
try:
Order(1002).pay()
except RuntimeError as error:
print("refused:", error)
try:
OrderLine("pen", 30, 0)
except ValueError as error:
print("refused:", error)
# printed: order 1001
# lines 2
# total 250
# discount 25
# payable 225
# paid True
# refused: order is paid
# refused: empty order
# refused: bad count
An entity holds a business rule of the shop and knows nothing about a database, a screen or the network, so it can be tested without them.Read moreThe problem. A shop gives 10% off every order from 200. If this rule lives in a web page, and again in a database query, the two copies soon disagree. To check the rule, you must start the page or the database. The most important knowledge of the shop is scattered and hard to test. The idea. An entity is a piece of data together with the business rules about it: what an order contains, how its total is counted, when it may be paid. It knows nothing about a database, a screen or the network. Clean architecture has one main rule, the dependency rule: outer code may know inner code, but inner code never knows outer code. Entities are the innermost code, so they depend on nothing. How to read the example. There are two entities: a line of an order and the order itself. The order sums its lines, gives 10% off from 200 and counts the amount to pay. It refuses to be paid while it is empty. The client code builds order 1001 with two lines and prints its numbers: the total is 250, the discount 25 and the amount to pay 225. It also tries to pay an empty order, and the entity refuses. In some languages the entity is a plain value with functions, not a class; its role is the same. When to use it. Make an entity for each concept of the business that has its own rules, such as an order or an account. Data without rules needs no entity: a simple structure is enough. A common mistake. An entity that saves itself to the database or formats itself for the screen. Then it depends on outer code, and its rules can no longer be tested alone. |