Entity

Design patterns / Clean architecture patterns
image

using System;
using System.Collections.Generic;
using System.Linq;

//client code
//no database and no screen anywhere below
var order = new Order(1001);
order.Add("pen", 30, 2);
order.Add("lamp", 190, 1);
Console.WriteLine($"order {order.Id}");
Console.WriteLine($"lines {order.Lines.Count}");
Console.WriteLine($"total {order.Total}");
Console.WriteLine($"discount {order.Discount}");
Console.WriteLine($"payable {order.Payable}");
order.Pay();
Console.WriteLine($"paid {order.Paid}");

//every rule below is refused by the entity itself
try
{
    order.Add("pen", 30, 1);
}
catch (InvalidOperationException error)
{
    Console.WriteLine($"refused: {error.Message}");
}

try
{
    new Order(1002).Pay();
}
catch (InvalidOperationException error)
{
    Console.WriteLine($"refused: {error.Message}");
}

try
{
    new OrderLine("chair", 30, 0);
}
catch (ArgumentException error)
{
    Console.WriteLine($"refused: {error.Message}");
}
//printed: order 1001
//         lines 2
//         total 250
//         discount 25
//         payable 225
//         paid True
//         refused: already paid
//         refused: empty order
//         refused: bad count

//entity: a record still guards its own rule, because a
//positional property may be re-declared with a check
record OrderLine(string Sku, int Price, int Count)
{
    public int Count { get; } = Count > 0
        ? Count
        : throw new ArgumentException("bad count");

    public int Cost => Price * Count;
}

//entity
sealed class Order
{
    private readonly List<OrderLine> lines = [];

    public Order(int id) => Id = id;

    public int Id { get; }

    public IReadOnlyList<OrderLine> Lines => lines;

    public bool Paid { get; private set; }

    //business rule: a paid order never changes
    public void Add(string sku, int price, int count)
    {
        if (Paid)
        {
            throw new InvalidOperationException(
                "already paid");
        }
        lines.Add(new OrderLine(sku, price, count));
    }

    public int Total => lines.Sum(line => line.Cost);

    //business rule: 10% off from 200
    public int Discount => Total >= 200 ? Total / 10 : 0;

    public int Payable => Total - Discount;

    //business rule: an empty order is never paid
    public void Pay()
    {
        if (lines.Count == 0)
        {
            throw new InvalidOperationException(
                "empty order");
        }
        Paid = true;
    }
}


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.