Entity

Design patterns / Clean architecture patterns
image

# entity: the rules of the shop speak with an error of
# their own, never with a bare string
class ShopRule < StandardError; end

# entity
class OrderLine
    attr_reader :sku, :price, :count

    def initialize(sku, price, count)
        raise ShopRule, "bad count" if count <= 0
        @sku = sku
        @price = price
        @count = count
        # a line never changes after it is born
        freeze
    end

    def cost = price * count
end

# entity
class Order
    attr_reader :id

    def initialize(id)
        @id = id
        @lines = []
        @paid = false
    end

    def add(sku, price, count)
        raise ShopRule, "order is paid" if @paid
        @lines << OrderLine.new(sku, price, count)
        self
    end

    # the inner list is never handed out as it is
    def lines = @lines.dup.freeze

    def size = @lines.size

    def total = @lines.sum(&:cost)

    # business rule: 10% off from 200
    def discount = total >= 200 ? total / 10 : 0

    def payable = total - discount

    # business rule: an empty order is never paid
    def pay
        raise ShopRule, "empty order" if @lines.empty?
        @paid = true
        self
    end

    def paid? = @paid
end

# client code
# no database and no screen anywhere above
order = Order.new(1001)
order.add("pen", 30, 2)
order.add("lamp", 190, 1)
puts "order #{order.id}"
puts "lines #{order.size}"
puts "total #{order.total}"
puts "discount #{order.discount}"
puts "payable #{order.payable}"

order.pay
puts "paid #{order.paid?}"

# every refusal comes from the rules themselves:
# no storage and no screen took part in them
begin
    order.add("pen", 30, 1)
rescue ShopRule => error
    puts "refused: #{error.message}"
end

begin
    Order.new(1002).pay
rescue ShopRule => error
    puts "refused: #{error.message}"
end

begin
    OrderLine.new("pen", 30, 0)
rescue ShopRule => error
    puts "refused: #{error.message}"
end

# the list handed out is frozen, so nobody adds a line
# behind the back of the rules above
begin
    order.lines << OrderLine.new("chair", 1, 1)
rescue FrozenError
    puts "refused: lines are frozen"
end
# printed: order 1001
#          lines 2
#          total 250
#          discount 25
#          payable 225
#          paid true
#          refused: order is paid
#          refused: empty order
#          refused: bad count
#          refused: lines are frozen


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 more

The 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.