<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en"><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://zlatozar.github.io/feed.xml" rel="self" type="application/atom+xml" /><link href="https://zlatozar.github.io/" rel="alternate" type="text/html" hreflang="en" /><updated>2026-11-28T14:12:00+00:00</updated><id>https://zlatozar.github.io/feed.xml</id><title type="html">Zlatozar Zhelyazkov</title><subtitle>Personal engineering journal of Zlatozar Zhelyazkov — notes on software architecture, domain-driven design, functional programming, compilers, and structured thinking.</subtitle><author><name>Zlatozar Zhelyazkov</name><email>zlatozar@gmail.com</email></author><entry><title type="html">EventStorming: From Sticky Notes to Bounded Contexts</title><link href="https://zlatozar.github.io/event-storming/" rel="alternate" type="text/html" title="EventStorming: From Sticky Notes to Bounded Contexts" /><published>2026-11-26T11:04:52+00:00</published><updated>2026-11-26T11:04:52+00:00</updated><id>https://zlatozar.github.io/event-storming</id><content type="html" xml:base="https://zlatozar.github.io/event-storming/"><![CDATA[<blockquote class="epigraph">
  <p>Garbage in, garbage out.</p>

  <p>— Early computing saying (1950s)</p>
</blockquote>

<h2 id="the-problem-we-need-to-solve">The Problem We Need to Solve</h2>

<p>One of the stakeholders has an idea in their head. They want us to turn it into a software
application. <strong>How is this supposed to happen?</strong></p>

<p>The best option is to write the idea down as a specification. Then we turn the
specification into a program, in the programming language of our choice. So far, so good.
But <strong>what is a specification?</strong></p>

<dl class="definition">
  <dt>specification <em>noun</em></dt>
  <dd>A step-by-step description of the process, with definitions given by the domain experts.</dd>
</dl>

<p>It is quite easy to understand what the experts want. What we need is a convenient way to
turn it into an executable program. This program should be:</p>

<ul>
  <li>broken into small modules (for fast builds and scalability)</li>
  <li>easy to understand for newcomers (or for you, six months later)</li>
  <li>maintainable (you can see the use cases at a glance)</li>
  <li>easy to extend with new features</li>
  <li>testable in isolation</li>
  <li>self-documenting</li>
</ul>

<p>If these requirements are not met, sooner or later the program becomes a
<a href="http://www.laputan.org/mud/">big ball of mud</a>.</p>

<blockquote class="callout callout--key">
  <p><strong>Key point</strong></p>

  <p>Misunderstood requirements add accidental complexity to a business domain that is
already complex.</p>
</blockquote>

<p>All engineering problems are solved on the drawing board first, right? Let’s begin.</p>

<h2 id="what-is-eventstorming">What Is EventStorming?</h2>

<p><strong>EventStorming</strong> is a workshop format created by Alberto Brandolini in 2013. EventStorming
is a form of organizational anthropology. It is all about discussing the flow of events in
your organization and modeling that flow in a way that is easy to understand. The
knowledge from an EventStorming session will later feed into other modeling techniques,
which give structure to the business flows that emerge. But the real value is in the
conversations. You can build a software system from the models. Or you can simply use
what you learned in the conversations to understand and improve the business processes
themselves. After all,
<a href="https://www.lambdabytes.io/posts/selearning/">software engineering is a learning process, and working code is a side effect</a>.</p>

<p>You can look at EventStorming in several ways:</p>

<ul>
  <li>as a step in translating the specification into a program</li>
  <li>as a way for programmers to show their understanding in a language that domain experts
can follow</li>
  <li>as a way to show stakeholders how the program will work</li>
</ul>

<p>Brandolini describes three formats. They differ in scope and in who is in the room:</p>

<ul>
  <li><strong>Big Picture:</strong> the whole business, or a large part of it. Many people, mostly events
and hot spots. The goal is a shared understanding and finding the biggest problems.</li>
  <li><strong>Process Modeling:</strong> one business process from start to end. It adds actors, commands,
policies, read models, and external systems.</li>
  <li><strong>Software Design:</strong> the same process, now with aggregates and candidate bounded
contexts. It is the direct input for the code.</li>
</ul>

<p>This guide follows one small session. It starts with a short, Big Picture-style timeline
of events, continues as Process Modeling (from “Commands” to “Read Models”), and ends with
Software Design (aggregates and boundaries). For a large domain with many teams, run a
Big Picture workshop first. Then model each interesting process in a separate session.</p>

<p>The important thing is that EventStorming happens with both <em>programmers</em> and <em>domain
experts</em> in the room. So <strong>programmer jargon</strong>, such as “it will be stored in the
database” or “invalidate the cache”, must not be used. The aim is to speak one common
language. In Domain-Driven Design (DDD) it is called the <strong>ubiquitous language</strong>. This
means that we start from the words and definitions of the domain experts and refine them
together with the experts. Programmers do not invent their own names for business
concepts.</p>

<p>The second important thing is to agree on how the meeting will go: <em>break the work into
small steps and discuss possible scenarios from a business point of view.</em></p>

<p>To keep it understandable for people who are not programmers, we use only colorful sticky
notes and a whiteboard. Most often it is a digital whiteboard, because it always has
enough space and never runs out of notes. It is also easy to move notes around quickly,
which is a big advantage.</p>

<blockquote class="callout callout--facilitator">
  <p><strong>Facilitator tip</strong></p>

  <p>Everything you discuss must go on the board as a sticky note: user, policy, command, and
so on. If you plan to discuss or check something later, add a concern note (a hot spot).</p>
</blockquote>

<h2 id="organizing-a-typical-eventstorming-session">Organizing a Typical EventStorming Session</h2>

<p><strong>What do we need to get started?</strong></p>

<ul>
  <li>First, a non-trivial problem in a specific domain that we want to automate, and a domain
expert who can explain it to us.</li>
  <li>Second, and much less important: a digital whiteboard with colorful sticky notes.</li>
</ul>

<p>The experts or stakeholders take the first step: they explain the task in a few
introductory words. One person “owns” the whiteboard and facilitates the dialogue between
the participants. Often this is one of the programmers, but it does not have to be. This
person explains the rules of the “game”. They also save the key steps as a document, so
that we can return to them later to reorganize things or add new features.</p>

<h2 id="in-the-beginning-was-the-empty-whiteboard">In the Beginning Was the Empty Whiteboard</h2>

<p>It always starts with a whiteboard. The facilitator prepares it like this:</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/whiteboard.jpg">
    <img src="/assets/images/event-storming/whiteboard.jpg" width="1641" height="951" loading="lazy" alt="An empty board with a color legend on the left, a Definitions area at the
              top, and a timeline arrow at the bottom that points to the right." />
  </a>
  <figcaption>The empty board: a legend on the left, definitions at the top, and a
    timeline that runs from left to right.</figcaption>
</figure>

<p>This way, everyone understands that the process runs from <strong>left</strong> to <strong>right</strong>, and knows
where to look for the definitions of terms. Make it clear that when things happen <em>at the
same time</em>, their notes are stacked vertically.</p>

<blockquote class="callout callout--note">
  <p><strong>Note</strong></p>

  <p>The exact colors do not matter. What matters is that the legend is always visible
and that everyone uses it the same way.</p>
</blockquote>

<h2 id="the-facilitator">The Facilitator</h2>

<p>The facilitator is responsible for the organization: who to invite and how to make people
<em>more active</em>. Invite people with questions (programmers, testers, designers) and people
with answers (domain experts). By “more active” I mean asking questions, and adding or
rearranging sticky notes. The facilitator stays neutral: they guide the process, not the
decisions. <strong>As the saying goes, success is a collective effort.</strong></p>

<blockquote class="callout callout--facilitator">
  <p><strong>Facilitator tip</strong></p>

  <p>Every participant can add sticky notes, so it is a good idea to share the board.
<a href="https://miro.com">Miro</a>, <a href="https://www.mural.co">Mural</a>, and
<a href="https://www.figma.com/figjam/">FigJam</a> support this.</p>

  <p>Open two whiteboards: one for the session and one to save its stages.</p>
</blockquote>

<h2 id="every-long-journey-begins-with-the-first-step">Every Long Journey Begins with the First Step</h2>

<p>The hardest part is the beginning, or more exactly, finding the thing that “ignites” the
process.</p>

<p>Do not forget that many things happen by chance. The deeper we go into the topic, the more
accurate our judgments become. So we can, and must, rework the previous steps. <strong>That is
incremental refinement.</strong> We cannot expect our first attempt to succeed. But because we
draw a picture instead of writing a document, we understand each other easily and changes
are cheap. So this should not bother us.</p>

<p>To start, we imagine that <em>something has already happened</em> and put a sticky note on the
whiteboard for it. The note says what happened, in the <strong>past tense</strong>, as a noun plus a
verb in the past tense: <code class="language-plaintext highlighter-rouge">Noun + Verb (past tense)</code>. For example, <strong>“Order placed”</strong> or
<strong>“Request verified”</strong>. Place it close to the legend, but not too close, because later we
may discover that something else must have happened before it. If you have assumptions,
resolve them <strong>later</strong>. For now, they are not a problem.</p>

<blockquote class="callout callout--modeling">
  <p><strong>Modeling tip</strong></p>

  <p>Try not to use CRUD terms such as “updated” and “deleted”. Ask what the change means for
the business: “Address changed” or “Order cancelled”, not “Order updated”.</p>
</blockquote>

<figure class="post-figure">
  <a href="/assets/images/event-storming/order-placed.jpg">
    <img src="/assets/images/event-storming/order-placed.jpg" width="1588" height="983" loading="lazy" alt="The board with one orange event note, Order placed, near the legend." />
  </a>
  <figcaption>The first event, placed close to the legend.</figcaption>
</figure>

<h2 id="from-event-to-event-to-the-end">From Event, to Event to the End</h2>

<p>A domain event (orange) represents something that changes the state of your business and
that other parts of the system care about.</p>

<ul>
  <li>If an action only changes what the user sees on the screen (a filter, a sort order, an
opened tab), it is not a domain event.</li>
  <li>If an action changes something the business cares about (an order is placed, a payment
is received, a customer is registered), then it <strong>is</strong> a domain event.</li>
</ul>

<p><strong>So what is an event?</strong> It is a <strong>fact</strong>. You cannot change it, just as you cannot go
back in time. We use it to mark what is done up to this point in time. Once an event is on
the board, the facilitator asks: <strong>“What should happen next?”</strong> <em>Take the smallest
possible step in the process.</em> We leave all technical steps out of the discussion and
place only events that the business cares about. Remember, domain experts are not
programmers.</p>

<blockquote class="callout callout--facilitator">
  <p><strong>Facilitator tip</strong></p>

  <p>Keep asking questions! <strong>What comes next? Are the existing events in the right order?
Could we change this flow?</strong></p>
</blockquote>

<p>Sometimes stakeholders do not have the most effective plan. They follow a process they
imagined themselves, or one created by
<a href="https://www.thoughtworks.com/insights/blog/applying-conways-law-improve-your-software-development">their organization</a>,
which is usually not optimized. Once the process is drawn on the board, it is easy to
question. <em>Be the driver of change.</em></p>

<blockquote class="callout callout--key">
  <p><strong>Key point</strong></p>

  <p>An event is the record of a state change that has already happened. We cannot reject an
event, so we control what causes it: the <em>command</em>. A command can come from a person, a
policy, or a timer. It is a request, and it can be rejected. The part of the system that
owns the data (later we call it the aggregate) checks its rules first, and only then
records the event. This way, every event leaves the system in a valid, known state. We
must also understand <em>why</em> each event happened, so that we can explain the reactions it
causes.</p>
</blockquote>

<h3 id="from-chaos-to-a-timeline">From Chaos to a Timeline</h3>

<p>Our example grows one note at a time, because it is small. With a larger domain and more
people, Brandolini suggests a faster start:</p>

<ol>
  <li><strong>Chaotic exploration.</strong> Everyone writes events at the same time, for 10–15 minutes,
without discussion. Duplicates and a wrong order are fine at this point.</li>
  <li><strong>Enforce the timeline.</strong> Together, sort the notes from left to right and remove
duplicates. Put a concern note on every disagreement and move on.</li>
  <li><strong>Find pivotal events.</strong> Mark the few events that change the process the most, for
example <em>Order placed</em> or <em>Order shipped</em>, with a vertical line. They split the
timeline into parts, and these parts are often the first hints of bounded contexts.</li>
  <li><strong>Walk the story.</strong> One person tells the story from left to right. Then walk it
backwards and ask for each event: “What must have happened before this?” Missing
events show up quickly.</li>
</ol>

<blockquote class="callout callout--facilitator">
  <p><strong>Facilitator tip</strong></p>

  <p>Timebox each step. A short step with a visible result keeps people active.</p>
</blockquote>

<h2 id="definitions-of-terms">Definitions of Terms</h2>

<p>If we decide to use the terms of the experts who give us the task, we must know what those
terms mean, right? That is why we introduce a new kind of note: the light green sticky
note. On it, we briefly describe terms whose meaning we do not know or that are
ambiguous. <em>Definitions keep the discussion consistent!</em></p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/definitions.jpg">
    <img src="/assets/images/event-storming/definitions.jpg" width="1588" height="983" loading="lazy" alt="Two green notes in the Definitions area. SKU: the smallest unit to buy.
              Order: list of SKUs." />
  </a>
  <figcaption>Light green notes at the top of the board define the terms.</figcaption>
</figure>

<p>The <a href="https://en.wikipedia.org/wiki/Law_of_identity">law of identity</a>: if we talk about
something, we must be sure that we are all talking about the same thing. That is why we
need definitions.</p>

<p>If two groups of experts use the same word with different meanings, write both
definitions and mark each with its group. Do not force one meaning. This is one of the
best hints for a bounded context boundary, which we will draw later.</p>

<h2 id="concerns-hot-spots">Concerns (Hot Spots)</h2>

<p>Concerns, open questions, and disagreements come up during the conversation. Do not stop
to solve them. Write each one on a purple note and put it next to the place where it came
up. We call these notes <strong>hot spots</strong>. Some can be resolved later. For others, it
is good to think more carefully about their <strong>software solution</strong>. If there are too many
of them on the board, it is a sign that:</p>

<ul>
  <li>the area we will work on is not well known,</li>
  <li>or we have not invited the right people,</li>
  <li>or, what matters most to us as programmers, the implementation will be quite difficult.</li>
</ul>

<p>It is vital to give these notes priorities (using tags on the notes!) and to work on them
in order of priority. At the end of the session, let everyone vote (for example, with
dots) on the concerns that matter most.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/concerns.jpg">
    <img src="/assets/images/event-storming/concerns.jpg" width="1645" height="949" loading="lazy" alt="The board legend now has a purple Concerns note under Events and
              Definitions." />
  </a>
  <figcaption>Purple notes record concerns.</figcaption>
</figure>

<blockquote class="callout callout--facilitator">
  <p><strong>Facilitator tip</strong></p>

  <p>When a discussion takes too long, write it on a concern note and move on. The note keeps
the question visible, and the session keeps its speed.</p>
</blockquote>

<h2 id="commands-or-who-command-triggers-what-event">Commands, or Who (Command) Triggers What (Event)</h2>

<p>A <strong>command</strong> is a request to the system to do something. It carries an intent: an
action, an interaction, or a decision. A command can be rejected. If it is accepted, it
has an effect: the receiving side changes its state, starts a task, or sends more
commands.</p>

<p><em>Fine, we have the events on the board. But are they caused by someone or something?</em> By
“someone” I mean a user, a scheduler, or the software itself (the program reacts, like a
falling domino). The request that asks the system to change is always a <code class="language-plaintext highlighter-rouge">Command</code>. Only
the sender differs: a person or a machine. We write commands in the <strong>imperative</strong> mood,
on blue sticky notes.</p>

<p>A command appears on the board in one of two places:</p>

<ol>
  <li><strong>After an actor (front-loading).</strong> A person sees some data, decides to act, and
issues the command: <code class="language-plaintext highlighter-rouge">[Read Model]</code> → <code class="language-plaintext highlighter-rouge">[Actor]</code> → <code class="language-plaintext highlighter-rouge">[Command]</code> → <code class="language-plaintext highlighter-rouge">[Event]</code>.</li>
  <li><strong>After a policy (back-loading).</strong> The system reacts to a past event and issues the
next command by itself: <code class="language-plaintext highlighter-rouge">[Event]</code> → <code class="language-plaintext highlighter-rouge">[Policy]</code> → <code class="language-plaintext highlighter-rouge">[Command]</code> → <code class="language-plaintext highlighter-rouge">[Next Event]</code>.</li>
</ol>

<p>We look at both loops in more detail in <a href="#policies-reactive-logic">Policies</a>.</p>

<h3 id="what-is-a-reaction">What Is a Reaction?</h3>

<p>A <strong>reaction</strong> is something that must happen because something else has happened. One
simple sentence captures it: <strong>“Do this <em>whenever</em> that happens.”</strong> “This” is the
reaction, and “that” is the event. <strong>The word “whenever” links the event to the reaction,
and together they form a policy (a plan of action).</strong> When people describe a process with
“whenever”, they are already describing an <em>event-driven system</em>.</p>

<p>A small side note. If you think about it, this is not only about software. There is always
a reason, voluntary or not, for something to happen, and then the fact (event) is there.
Once we have it, we can act. In other words, we apply different policies, as we will see
later.</p>

<p>We must keep reviewing the things we put on the board. Now is the time to ask: <strong>“Is this
the right flow?”</strong> or <strong>“Who raises this command at this time? With what rights?”</strong> The
answers can lead to a rearrangement. Keep in mind that stakeholders do not know the best
algorithms, but they know the process best. Keep asking.</p>

<p>We add a small yellow sticky note to a command when a person issues it. This note is the
<strong>actor</strong>. Write the role of the person, for example <em>Customer</em> or <em>Support</em>, not the name
of a specific person. On our board, the note <em>User rights</em> also reminds us that the actor
needs certain rights to place an order. When a command has no actor note, a policy or a
timer issues it: it is triggered by the system.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/command.jpg">
    <img src="/assets/images/event-storming/command.jpg" width="1568" height="996" loading="lazy" alt="A blue Place order command with a small yellow User rights note. After it,
              two stacked orange events: Order placed and Audit log created." />
  </a>
  <figcaption>A blue command in front of its event. The small yellow note shows who may
    issue it.</figcaption>
</figure>

<p><em>When we communicate with commands, we must think about failures. Why does a command
fail?</em> A command can be rejected for a <strong>business</strong> reason (for example, not enough
credit). A rejected command changes nothing. But if the business cares about the
rejection, put it on the board as an event, for example <em>Payment declined</em>. Then ask the
experts what <strong>compensating actions</strong> the system must take for the steps that already
happened, for example <em>Cancel order</em> after <em>Order placed</em>. These actions are also
commands. When the system triggers them itself, through a policy, they do not get a
yellow sticky note. When a person must do them (for example, a support person calls the
customer), add the actor note.</p>

<h2 id="external-systems">External Systems</h2>

<p>These are systems we have <strong>no control</strong> over, and we do not know the details of how they
work. We must show the connection to them.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/external-system.jpg">
    <img src="/assets/images/event-storming/external-system.jpg" width="1530" height="1020" loading="lazy" alt="The Validate user command calls a red Backend System note, which returns to
              the User validated event. Two purple concerns next to it: It is not
              reliable, and Could slow down the whole system." />
  </a>
  <figcaption>A red note marks an external system and its connections. Purple notes record
    concerns about it.</figcaption>
</figure>

<blockquote class="callout callout--modeling">
  <p><strong>Modeling tip</strong></p>

  <p>Never place a command such as <strong>“Ask external system”</strong>. That is a technical detail. In
the first phase, when you start with the events, focus on business facts. Add the
external system later, when you ask what causes an event. Instead of “Ask external
system”, place a command that has business value, for example <strong>“Validate user”</strong>.</p>
</blockquote>

<p>These systems are especially important, because they can change in a direction we do not
want. In Domain-Driven Design, the usual practice is to put a so-called
<a href="https://martinfowler.com/articles/refactoring-external-service.html">anticorruption layer</a>
between their model and ours. In short, we take the data we need from the external system
and translate it into the terms of <strong>our</strong> model, so their changes stay in one place. The
same adapter is a good place to protect ourselves when the connection fails, with caching
and request retries. But that is a technical concern, not part of the translation.</p>

<h2 id="events-triggered-by-time">Events Triggered by Time</h2>

<p>Yes, this is also possible. Some events happen only because time has passed: the end of
the day, a deadline, or a timeout. No user issues a command here, so on our board the
arrow goes directly from one event to the next: <code class="language-plaintext highlighter-rouge">Event</code> → <code class="language-plaintext highlighter-rouge">Event</code>.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/time-triggered-events.jpg">
    <img src="/assets/images/event-storming/time-triggered-events.jpg" width="1556" height="1003" loading="lazy" alt="The event Log rotating ran over one hour, with an arrow to the event
              Rotating log failed." />
  </a>
  <figcaption>A time event leads to the next event. The rule between them is
    implied.</figcaption>
</figure>

<p>Read the board like this. <strong>“Log rotating ran over one hour”</strong> is the time event: a clock
or a timer tells us that one hour has passed. Strictly speaking, a rule is hidden between
the two notes: <em>“Whenever log rotation runs longer than one hour, stop it and mark it as
failed.”</em> That rule is a policy, and it issues a command. The direct arrow is a useful
shortcut on a quick board. When the rule matters to the business, make it visible: add
the policy and the command between the two events.</p>

<blockquote class="callout callout--modeling">
  <p><strong>Modeling tip</strong></p>

  <p>Draw a small clock on time events, so they stand out. Our example comes from operations.
In a business process, typical time events are <em>“Payment deadline passed”</em>, <em>“Day
closed”</em>, or <em>“Trial period ended”</em>.</p>
</blockquote>

<p><strong>This covers all kinds of time-triggered events: cron jobs, monitors, and schedulers.</strong></p>

<h2 id="policies-reactive-logic">Policies (Reactive Logic)</h2>

<p>A policy automatically triggers a new action (for example, “Send rejection email”).</p>

<p>An event together with the reaction to it forms a <strong>policy</strong>. The name fits, because a
policy is a business rule, for example: <strong>“Whenever someone changes their configuration,
alert the customer.”</strong></p>

<p>A reaction, or a whole policy, does not have to be software. For example, “activate
order” can be a manual step: a support person checks the details by hand. So
EventStorming helps you to discover the manual processes in your organization, not only
to design new software.</p>

<p>To show a manual policy, put a small yellow actor note on it. On our board in the next
section, the <em>Support</em> note on <em>Inform support team</em> means that a support person does
this step.</p>

<blockquote class="callout callout--facilitator">
  <p><strong>Facilitator tip</strong></p>

  <p>When you hear people say “Whenever this happens, we do that”, it is a policy. You can
start a policy with “Whenever …”.</p>
</blockquote>

<p>From the domain experts’ point of view, this is the most important part of the model. We
are building a kind of crossroads: a place where we must make a decision. Note that the
domain experts decide which roads exist. At this stage we cannot ask questions such as
<strong>“What if there is no connection?”</strong> or <strong>“What if the system crashes?”</strong> Those questions
belong to a later, technical stage of system design. Policies are the <strong>“possible
consequences”</strong> of an event (fact).</p>

<p>The question is <strong>“What do we do when this event shows up?”</strong> or <strong>“What are the next
commands that will complete the next step?”</strong> That is why policy notes are placed after
the fact (event). Policies should show which commands must be issued next, so that the
system can move to its <em>next state</em>. Note that a policy can issue more than one command,
and these commands can run in parallel. The number comes from the business rule, not from
technical needs such as speed. Still, keep it low: every extra command is one more path to
test and maintain. A policy can also <em>choose</em> one command out of several, based on a
condition. For example: whenever <em>Payment failed</em>, if it is the first attempt, <em>Retry
payment</em>; otherwise, <em>Cancel order</em>. Write the condition on the policy note. (In code,
such a choice is often a Strategy pattern, but that is a detail for later.)</p>

<p>Policies make us look at the system from all angles. At the same time, at this stage we
get an overall view. The questions to ask are <strong>“Great, we have this fact. How does it
change the system?”</strong> and <strong>“Who is waiting for this fact to appear, so they can react?”</strong>
There are always side paths.</p>

<p>More informally, a policy is a <code class="language-plaintext highlighter-rouge">When–Then</code> clause: <code class="language-plaintext highlighter-rouge">When</code> an event shows up, <code class="language-plaintext highlighter-rouge">Then</code>
trigger the matching command(s).</p>

<p><em>Most failures in computer systems start with a wrong assumption.</em> When we model only
cause and effect, we can better decide how to react to anything. We do not make false
assumptions about outcomes: not only successful outcomes, but also errors and other
less-than-ideal events.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/policy.jpg">
    <img src="/assets/images/event-storming/policy.jpg" width="1527" height="1023" loading="lazy" alt="Pink policy notes after events: New order after Order placed leads to the
              commands Validate user and Create audit log; Valid user after User validated
              leads to Request configuration." />
  </a>
  <figcaption>Pink policy notes sit after an event and lead to the next
    commands.</figcaption>
</figure>

<blockquote class="callout callout--modeling">
  <p><strong>Modeling tip</strong></p>

  <p>On our board, <em>User validated</em> is followed by two policies, <em>Valid user</em> and <em>Invalid
user</em>. This hides two different outcomes in one event. It is clearer to use two events,
<em>User validated</em> and <em>User rejected</em>, each with its own policy. The bounded context
diagram later in this article does exactly this.</p>
</blockquote>

<p>One policy can trigger more than one command, or none. If it triggers none, we simply
remove the policy note. It is also fine to have policies with the same name after
different events. This shows that different events trigger the same policy.</p>

<p>So a policy listens to domain events and, when its condition holds, issues commands. This
is <strong>reactive behavior</strong>. Systems built mostly from such <code class="language-plaintext highlighter-rouge">Event</code> → <code class="language-plaintext highlighter-rouge">Policy</code> → <code class="language-plaintext highlighter-rouge">Command</code>
chains are <em>event-driven</em>, and this is one way to build <strong>reactive systems</strong>.</p>

<p>Now we can look at the two loops from
<a href="#commands-or-who-command-triggers-what-event">Commands</a> in more detail:</p>

<ol>
  <li><strong>The user-driven loop</strong> (<code class="language-plaintext highlighter-rouge">Command</code> → <code class="language-plaintext highlighter-rouge">Event</code>). This is the most common path. A user
(or another external system) wants to make something happen. They have an intent.
    <ul>
      <li><strong>Read model (green):</strong> before deciding, the user needs information. They look at a
read model (for example, a “Shopping cart” or “Product availability”).</li>
      <li><strong>Command (blue):</strong> the user acts on that information and issues a command (for
example, <em>Place order</em> or <em>Check out</em>). The command represents their intent.</li>
      <li><strong>Domain event (orange):</strong> if the aggregate accepts the command, it publishes a
domain event (for example, <em>Order placed</em> or <em>Payment received</em>). This is now a fact
that cannot change.</li>
    </ul>
  </li>
  <li><strong>The system reactive loop</strong> (<code class="language-plaintext highlighter-rouge">Event</code> → <code class="language-plaintext highlighter-rouge">Policy</code> → <code class="language-plaintext highlighter-rouge">Command</code>). This is the automated
“falling domino” part of your system. Something has already happened, and now the
system must react to that fact.
    <ul>
      <li><strong>Domain event (orange):</strong> the loop starts with a domain event (for example, <em>Order
placed</em>). This event is a fact that has just happened.</li>
      <li><strong>Policy (pink on our boards):</strong> a policy (the “whenever” rule) listens for this
specific event. The policy’s job is to <strong>decide</strong>: “Whenever this event happens, what
automated action do we take next?” (For example, whenever <em>Order placed</em> happens, we
need to prepare the shipment.)</li>
      <li><strong>Command (blue):</strong> the policy then automatically triggers a new command (for
example, <em>Prepare shipment</em>). This command starts its own loop: it goes to another
aggregate and produces another event (for example, <em>Shipment prepared</em>).</li>
    </ul>
  </li>
</ol>

<h2 id="read-models-or-data-requirements">Read Models, or Data Requirements</h2>

<p>A read model can be a specific part of the UI, or a record that the user needs in order to
carry out a command (action). <strong>It represents what the user or system needs to see before
taking action.</strong> A read model includes all the data that must be available before an
action can be taken, whether it comes from the database or from an external system. Note
that a read model is not part of the aggregate. It is only a way to present data to the
user or system.</p>

<p>Do not try to draw every screen or every specific type. Use read models to highlight
important data requirements. Use them when manual work is needed, for example by a support
team.</p>

<p>Place a read model where a decision is made:</p>

<ul>
  <li><strong>In front of a command that a user issues,</strong> when the user needs data to decide. On our
board, <em>Configuration</em> stands before <em>Place order</em>.</li>
  <li><strong>Between an event and a policy,</strong> when the policy needs data to decide what to do next.
On our board, <em>Log rotating error</em> stands between <em>Rotating log failed</em> and <em>Inform
support team</em>.</li>
</ul>

<p>Events update read models, and read models feed decisions. A read model never stands
between a command and its event.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/read-model.jpg">
    <img src="/assets/images/event-storming/read-model.jpg" width="1484" height="1052" loading="lazy" alt="Green read model notes on the board: Configuration in front of the Place
              order command, and Log rotating error after the Rotating log failed event,
              followed by the Inform support team policy with a yellow Support role." />
  </a>
  <figcaption>Green read model notes show the data needed before an
    action.</figcaption>
</figure>

<blockquote class="callout callout--modeling">
  <p><strong>Modeling tip</strong></p>

  <p>You can use a read model to outline a very basic UI that triggers a command. What must
the user know before pressing the button?</p>
</blockquote>

<h3 id="read-models-in-code-views">Read Models in Code (Views)</h3>

<p>On the board, a read model is the information a person (or a policy) needs to make a
decision. In code, it is often a <strong>projection</strong>, also called a <strong>view</strong>: a read-only data
shape built from domain events for one screen or one query. This is the read side of
CQRS (Command Query Responsibility Segregation). A projection is updated when events
arrive, usually asynchronously, so it can be a little behind the aggregates. Nobody
writes to it directly. To change data, send a command to an aggregate.</p>

<blockquote class="callout callout--modeling">
  <p><strong>Modeling tip</strong></p>

  <p>When you look for aggregates, ask: <strong>“Is the data we are changing part of an invariant?
Can the user change it directly?”</strong> If not, it is a read model (a view), not an
aggregate. You are modeling data, not a process.</p>
</blockquote>

<h2 id="aggregates-focus-on-behavior-not-data">Aggregates: Focus on Behavior, Not Data</h2>

<p><em>Think of an aggregate as a group of commands that must check the same business rules on
the same data. It is the only way to change that data. Aggregates are the <strong>invariant
keepers</strong> of the system. They keep their own state consistent and control the moves
between states.</em></p>

<blockquote class="callout callout--note">
  <p><strong>Note</strong></p>

  <p>Do not confuse the large yellow aggregate note with the small yellow actor note. The
actor is the person (role) who issues a command. The aggregate is the part of the system
that accepts or rejects that command. Newer EventStorming material calls the large
yellow note a <em>constraint</em>, because business people rarely say “aggregate”.</p>
</blockquote>

<p>From the programmers’ point of view, this is perhaps the most important step. Aggregates
are the building blocks for the next step, where we draw the bounded contexts and, later,
the microservices. Do not mix up these three boundaries:</p>

<ul>
  <li>An <strong>aggregate</strong> is a <em>consistency</em> boundary. Its rules (invariants) are true after
every command, and one transaction changes only one aggregate.</li>
  <li>A <strong>bounded context</strong> is a <em>model and language</em> boundary. Inside it, every term has one
meaning. It usually holds several aggregates.</li>
  <li>A <strong>microservice</strong> is a <em>deployment</em> boundary. It often matches one bounded context. But
one context can be split into several services, and one service should not span two
contexts.</li>
</ul>

<p>The idea is to group the commands that must check the same business rules on the same
data in the domain. On top of this group we build access logic and define rules for how
an outside user can invoke the commands. This way we take control and check that all
invariants hold. That role belongs to the <strong>aggregate</strong>: the entry point for every
outside call that wants to change its data (trigger an event through a command). <strong>The
aggregate rules the moves between states.</strong> In the next phase of design, when we turn the
model into code, we must provide methods that change this state.</p>

<p>An aggregate groups the commands it accepts and the events it records. Each command is
handled by exactly one aggregate. The aggregate checks its rules against its current
data and, if the command is accepted, records one or more events. Reactions (policies)
are <em>not</em> inside the aggregate. They sit between aggregates: they listen to events and
send commands, often to another aggregate or another context.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/aggregate-commands-events.svg">
    <img src="/assets/images/event-storming/aggregate-commands-events.svg" width="610" height="320" loading="lazy" alt="Three blue commands on the left, one tall yellow Order aggregate in the
              middle, and orange events on the right. Each command produces one or more
              events." />
  </a>
  <figcaption>The aggregate sits between its commands and the events they produce.
    Redrawn after Vlad Khononov, <em>Learning Domain-Driven Design</em>,
    ch. 12.</figcaption>
</figure>

<p>That is why the aggregate sticky note sits between the command and the event. On our
board below, the aggregate note sits on top of each command–event pair to save space. It
means the same thing: the command goes to the aggregate, and the aggregate produces the
event. <strong>Aggregates pair commands with events.</strong> An aggregate exposes one method per
command, and each method makes a particular event (or events) happen. This way the
system moves in a known, predefined direction. It also means that all directions should
be listed on the whiteboard.</p>

<p><em>The name of the unit must be a noun.</em> Name it after the business concept whose rules it
protects (for example, <em>Order</em>), not after a database table. We place an aggregate on
every command–event pair, and the same aggregate name may repeat. This should not worry
us. On the contrary, it will help us in the next step of the EventStorming session.</p>

<p>Keep aggregates small. Most aggregates have one root entity plus some value objects. Some
have two or three entities. This is a heuristic, not a rule. The real test is the
invariant: put inside the aggregate only the data that its rules need. If it holds data
that no rule needs, or if many users often change it at the same time and conflict, the
aggregate should be split.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/aggregate.jpg">
    <img src="/assets/images/event-storming/aggregate.jpg" width="1428" height="1093" loading="lazy" alt="The full board with yellow aggregate notes (Order, User, Configuration,
              AuditLog) placed above their command and event pairs." />
  </a>
  <figcaption>Yellow aggregate notes on top of each command–event pair. Names may
    repeat.</figcaption>
</figure>

<p><em>The aggregate keeps the state, and this state must survive between commands.</em> To decide
on the next command, the aggregate must know what happened before. So, when we turn the
model into code, we persist every aggregate: either its current state, or the list of its
events (<em>event sourcing</em>). There is one <em>repository</em> per aggregate type. It loads the
whole aggregate by its ID and saves it in one transaction. A policy that must remember
earlier events (for example, “wait for both <em>Payment received</em> and <em>Stock reserved</em>”)
also keeps state. In code, it becomes a <em>process manager</em> (also called a saga).</p>

<blockquote class="callout callout--modeling">
  <p><strong>Modeling tip</strong></p>

  <p>The aggregate is responsible for keeping the invariants, so its state is always
consistent with its data. Use the “No” rule to find these invariants. Do not ask <em>“What
data is here?”</em> Instead, ask: <em>“Which rules must be checked together to say ‘No’ to a
command?”</em> For example, if you cannot <em>Cancel order</em> without checking the <em>Shipping
status</em>, and the answer must be correct at the moment of the click, then Order and
Shipping belong in the same consistency boundary (aggregate). But first ask the experts:
<em>“Is a short delay acceptable?”</em> Usually it is. Then keep them as separate aggregates. A
policy reacts to <em>Order cancelled</em> and sends <em>Stop shipment</em>. If the parcel has already
left, a compensating action follows, for example <em>Request return</em>.</p>
</blockquote>

<figure class="post-figure">
  <a href="/assets/images/event-storming/system-bounded-contexts.svg">
    <img src="/assets/images/event-storming/system-bounded-contexts.svg" width="1000" height="510" loading="lazy" alt="Three dashed boxes for the Ordering, Users, and Audit contexts. Each holds
              commands, one aggregate, and events. Pink policies between the boxes connect
              an event in one context to a command in another." />
  </a>
  <figcaption>The system split into bounded contexts. Policies connect them. Redrawn
    after Vlad Khononov, <em>Learning Domain-Driven Design</em>, ch. 12.</figcaption>
</figure>

<h3 id="when-it-is-hard-to-tell-two-aggregates-apart">When It Is Hard to Tell Two Aggregates Apart</h3>

<p>Ask these questions:</p>

<ul>
  <li>What is the definition of the aggregate?</li>
  <li>How do we tell one from the other?</li>
  <li><strong>What is its identity?</strong></li>
  <li>Which events bring it into existence?</li>
</ul>

<p>If an aggregate feels too big because it “changes too much data”, it is a sign that you
are modeling <strong>data</strong> instead of <strong>process</strong>. Break it apart by asking: <em>“Can this command
succeed while the other part of the data is changing?”</em> If the answer is yes, they are
separate aggregates.</p>

<h2 id="programmers-take-responsibility">Programmers Take Responsibility</h2>

<p>Until now, the domain experts led the discussion. From here on, the programmers lead,
because we now draw the service boundaries. But the domain experts should stay in the
room. Only they can confirm that an aggregate protects the right business rules and that
a policy is correct. They also know where a word changes its meaning, and that is usually
where a bounded context ends. Their role changes from telling the story to checking our
design.</p>

<p>It is very important to save this state of the board, because we will need it when we add
new features or refactor!</p>

<h2 id="drawing-the-microservice-boundaries">Drawing the Microservice Boundaries</h2>

<p>A <strong>bounded context</strong> is the boundary inside which one model and one language are valid.
Inside a context, no term can be ambiguous. The same word can mean different things in
two contexts: a <em>Product</em> in the Catalog context (description, photos) is not the same as
a <em>Product</em> in the Warehouse context (weight, shelf). In code, a context is a relatively
standalone part of the system, with its own model and data. It is usually a separate
microservice, but not always. Here we must be creative and trust our instincts. Here are
some guidelines.</p>

<p><strong>The first and most important step is to remove the time factor.</strong> Time no longer exists
for us, so the current order of the events (facts) does not matter. Delete the timeline
from the whiteboard.</p>

<p><strong>Then we merge all units with the same aggregate name into one!</strong> But first check that
the name means the same thing in both places. If <em>Order</em> means one thing to sales and
another thing to shipping, these are two different models, and they belong in two
different bounded contexts. Since we use a digital whiteboard, the arrows move with the
notes. <strong>The arrows show the communication channels, which are event-driven.</strong></p>

<p>The next step is to group aggregates whose names are not the same but <em>close</em>, because
they belong together. Good signs are: they use the same terms (the same definitions), many
policies connect them, they serve the same business capability, and the same experts know
them. A word that changes its meaning, or a different group of experts, is a strong sign
of a boundary.</p>

<p>Here we have to make two reservations:</p>

<ol>
  <li><strong>Load.</strong> Ask: <em>“Could this service become a bottleneck?”</em> If one part of a context is
called much more often than the rest, we can deploy that part as a separate service
and scale it alone. This changes the deployment, not the model. It is still the same
bounded context.</li>
  <li><strong>Consistency.</strong> One transaction changes only one aggregate. A rule that must be true
<em>immediately</em> belongs inside one aggregate. Between aggregates, and always between
contexts, we accept <em>eventual consistency</em>: an event is published, a policy reacts,
and the next command runs in its own transaction. A service should never need a
distributed transaction, or a synchronous call to another service, to save its own
data.</li>
</ol>

<figure class="post-figure">
  <a href="/assets/images/event-storming/bounded-context.jpg">
    <img src="/assets/images/event-storming/bounded-context.jpg" width="1446" height="1079" loading="lazy" alt="The board without a timeline. Notes with the same aggregate name are merged
              and grouped into boundaries, with arrows between the groups." />
  </a>
  <figcaption>Without the timeline, notes with the same aggregate are merged into
    boundaries.</figcaption>
</figure>

<blockquote class="callout callout--modeling">
  <p><strong>Modeling tip</strong></p>

  <p>An aggregate often has a lifecycle, for example <em>Placed → Paid → Shipped</em>, or
<em>Cancelled</em>. It is very common to implement it as a small <em>state machine</em> inside the
aggregate. Each command is allowed only in some states, and the aggregate rejects it in
the others. A long-running process that spans several aggregates or contexts has its own
state machine in a <em>process manager</em> (saga). Both store their state through a
repository.</p>
</blockquote>

<h3 id="relationships-between-contexts">Relationships Between Contexts</h3>

<p>The arrows between the groups show that contexts depend on each other. DDD gives names to
these relationships, and we draw them on a <strong>context map</strong>. The patterns describe how the
teams and their models relate, not how the data travels:</p>

<ul>
  <li><strong>Shared Kernel:</strong> two contexts share a small part of the model (and its code). Both
teams must agree on every change to it.</li>
  <li><strong>Customer/Supplier:</strong> the downstream team (customer) depends on the upstream team
(supplier). The supplier takes the customer’s needs into account when it plans changes.</li>
  <li><strong>Conformist:</strong> the downstream team uses the upstream model as it is, because it cannot
influence it and a translation is not worth the cost.</li>
  <li><strong>Anticorruption Layer:</strong> the downstream team builds a translation layer, so that the
upstream model does not leak into its own model.</li>
  <li><strong>Open Host Service:</strong> the upstream context offers one well-defined API (protocol) for
all its consumers, instead of a custom integration for each one.</li>
  <li><strong>Published Language:</strong> a documented exchange format, for example a schema for events or
messages. It is often used together with an Open Host Service.</li>
</ul>

<p>The DDD literature also describes <strong>Partnership</strong> and <strong>Separate Ways</strong>. For more detail,
see <a href="https://github.com/ddd-crew/context-mapping">DDD Crew: Context Mapping</a>.</p>

<p>Each of these relationships can be implemented in two ways:</p>

<ul>
  <li><strong>Synchronous (request/response):</strong> one context calls another and waits for the answer,
for example over REST. It is simple, but both sides must be up at the same time.</li>
  <li><strong>Asynchronous (events):</strong> one context publishes a domain event, and the other reacts to
it. This is what the policies between our groups show: an event in one context triggers
a command in another. The policy usually lives in the context that reacts. The contexts
are decoupled in time, and the data becomes <em>eventually consistent</em>.</li>
</ul>

<p>Prefer asynchronous integration through policies. Use a synchronous call only when the
caller cannot continue without an immediate answer.</p>

<blockquote class="callout callout--note">
  <p><strong>Note</strong></p>

  <p>An external system is not part of <em>our</em> bounded contexts. It has its own model and
language, which we do not control. On the context map we draw it as a separate context,
and we choose how to integrate with it: translate its model with an anticorruption
layer, or accept its model as it is (Conformist).</p>
</blockquote>

<h2 id="adding-new-features">Adding New Features</h2>

<p>When a new requirement arrives, we take a step back to the <em>aggregate phase</em>, where the
timeline still exists. We do not start from an empty board. We take the saved board, find
the part of the timeline that the new requirement changes, and run a short session on that
part with the right domain experts. Then we check the new events and commands against the
existing aggregates and boundaries. We try to keep the previous split into services, if
possible. Either a new microservice may appear, or new functionality may be added to an
existing aggregate. Only careful analysis will tell. Once we agree, we save the new board
as a document and continue with the code changes.</p>

<p>It is important to keep each stage of our work, because we can use it when we add new
features or revisit old decisions. It is also documentation for new team members.</p>

<h2 id="the-picture-that-explains-everything">The Picture That Explains Everything</h2>

<blockquote class="epigraph">
  <p>All models are wrong, but some are useful.</p>

  <p>— George E. P. Box</p>
</blockquote>

<p>Brandolini calls this diagram “the picture that explains everything”. It shows how all
the notes we used fit together.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/event-storming.png">
    <img src="/assets/images/event-storming/event-storming.png" width="1421" height="1099" loading="lazy" alt="A cycle: User issues a Command, which leads to a Domain Event. The event
              triggers a Policy, which issues a new Command. The event also updates a
              Read Model, which the User reads. An External System also produces Domain
              Events." />
  </a>
  <figcaption>All the building blocks in one cycle, after Alberto Brandolini's
    "picture that explains everything".</figcaption>
</figure>

<p>In words, the picture says this. <strong>The user</strong> sends operation requests, called
<strong>commands</strong>, to the system. To decide what to send, the user uses information from the
system (from the UI or triggered automatically), shown as a <strong>read model</strong>, plus
information from the outside world and their own feelings and thoughts. A command might
cause a <em>state change</em> in the system, which produces <strong>domain events</strong>. These events can
trigger <strong>policies</strong>, which might issue new commands based on the information in those
events and on the system’s state. <strong>External systems</strong> can also produce events, which we
translate into our own domain events. The domain events also update the read models, so
the user gets new information from the system, and the cycle repeats.</p>

<h2 id="relation-to-user-stories">Relation to User Stories</h2>

<p>The
<a href="https://ibm-cloud-architecture.github.io/refarch-eda/methodology/event-storming/">IBM Event-Driven Reference Architecture</a>
shows a simple way to turn the board into user stories. The commands and policies related
to events can be described as <strong>user stories</strong>, because actors issue commands and make
decisions. An actor can also be a system.</p>

<p>An event is the result, or outcome, of a user story. Events can be added to the acceptance
criteria of user stories, to verify that the event really happens.</p>

<figure class="post-figure">
  <a href="/assets/images/event-storming/user-stories.png">
    <img src="/assets/images/event-storming/user-stories.png" width="720" height="270" loading="lazy" alt="Actor, commands, policies (whenever), data, and events mapped into two
              story templates: As an actor I want to … so that I can read …, and As an
              actor I want to … so that I can generate event …." />
  </a>
  <figcaption>From sticky notes to user stories. Image: IBM Event-Driven Reference
    Architecture.</figcaption>
</figure>

<h2 id="next-step-domain-driven-design">Next Step: Domain-Driven Design</h2>

<p>The most effective way to give structure to an event-driven system (one that we model with
events) is Domain-Driven Design. An EventStorming session models business process flows.
Domain-Driven Design gives us the discipline to turn those flows into a structured
software application. Here is a short example of what DDD says about aggregates. Vaughn
Vernon calls it a rule in <em>Implementing Domain-Driven Design</em>:
<a href="https://www.informit.com/articles/article.aspx?p=2020371&amp;seqNum=4">reference other aggregates by identity</a>.
An aggregate keeps only the ID of another aggregate, never a direct object reference to
it. This keeps aggregates small and isolated, and it makes it clear that one transaction
changes only one aggregate. It also saves memory, because the other aggregate is not
loaded eagerly. When we need it, we load it by its ID from its repository.</p>

<h2 id="resources">Resources</h2>

<ul>
  <li><a href="https://www.youtube.com/watch?v=QwOrbYTaDOY">Introduction to EventStorming (video)</a></li>
  <li><a href="https://www.youtube.com/watch?v=3-_0ZcI2SYc">Bounded Context briefly (video)</a></li>
  <li><a href="https://medium.com/redelastic/corporate-arts-crafts-modelling-reactive-systems-with-event-storming-73c6236f5dd7">EventStorming and Reactive Systems</a></li>
  <li><a href="https://www.youtube.com/watch?v=WvkBKvMnyuc">A more practical example (video)</a></li>
  <li><a href="https://github.com/mariuszgil/awesome-eventstorming">Awesome EventStorming</a></li>
</ul>]]></content><author><name>Zlatozar Zhelyazkov</name></author><category term="Architecture" /><category term="event-storming" /><category term="ddd" /><category term="domain-modeling" /><category term="bounded-context" /><category term="aggregates" /><category term="microservices" /><summary type="html"><![CDATA[How to run an EventStorming session step by step: events, definitions, concerns, commands, external systems, policies, read models, aggregates, and drawing bounded contexts.]]></summary></entry><entry><title type="html">Why Warnier/Orr Thinking Still Matters</title><link href="https://zlatozar.github.io/warnier-orr-diagrams/" rel="alternate" type="text/html" title="Why Warnier/Orr Thinking Still Matters" /><published>2026-11-22T08:00:00+00:00</published><updated>2026-11-22T08:00:00+00:00</updated><id>https://zlatozar.github.io/warnier-orr-diagrams</id><content type="html" xml:base="https://zlatozar.github.io/warnier-orr-diagrams/"><![CDATA[<p>A ticket lands on your board:</p>

<blockquote>
  <p><em>Monthly sales report. For each store, list every sale and return, then the store’s net
total. End with a grand total. Finance closes the month with it.</em></p>

  <div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>$ sales-report 2026-11 stores.csv sales.csv
</code></pre></div>  </div>

  <p><em>The arguments are the month, the list of all stores, and the month’s sales.</em></p>
</blockquote>

<p>Where do you start? Most of us open the CSV file and write a loop. Then the questions
arrive one by one. Is a store with no sales an error? What if a row has a broken amount?
Where does the formatting go? How many classes do we need?</p>

<p>DDD helps us find the bounded context and its language. Hexagonal Architecture keeps files
and databases out of the core. But both say little about the shape of the code <em>inside</em>
one use case: which types, which functions, which loop sits inside which, and where each
check belongs.</p>

<p>Jean-Dominique Warnier and Ken Orr answered this question in the 1970s: <strong>start from the
output</strong>. The output gives the shape of the data, and the data gives the structure of a
program. Kirk Hansen puts it in three rules. A <em>sequence</em> (different parts, each once, in
a fixed order) becomes statements one after another. A <em>selection</em> (one part or another)
becomes an <code class="language-plaintext highlighter-rouge">if</code>. This post applies these rules on purpose, with modern Python and contemporary
names.</p>

<hr />

<h2 id="where-warnierorr-fits">Where Warnier/Orr Fits</h2>

<p>Warnier/Orr is not a rival of DDD or Hexagonal Architecture. It works at a finer zoom:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Bounded Context     Which model? Which words?                DDD (strategic)
└─ Hexagon          What is core? What is an adapter?        Hexagonal Architecture
   └─ One use case  Which types, functions, loops, checks?   Warnier/Orr
</code></pre></div></div>

<p>DDD and Hexagonal Architecture draw the big boxes. Warnier/Orr fills one of them, from the
raw input at one edge to the finished output at the other. It also shares the core ideas
of functional programming: data first, pure functions, no shared state. Every block schema
(programming logic) could be represented by</p>

<h2 id="the-mindset-five-questions">The Mindset: Five Questions</h2>

<p>You do not have to draw diagrams to use Warnier/Orr. You have to ask five questions
before you write code:</p>

<ol>
  <li><strong>What comes out?</strong> Write a sample of the output by hand, with real values. Include
the bad case: what does the user see when the input is wrong?</li>
  <li><strong>How is it nested?</strong> For each item on the sample, ask how often it is printed. The
grand total is printed once per report, the net total once per store, and the amount
once per transaction. Report, store, and transaction are the levels. Each store sits
inside the report, and each transaction sits inside a store. That nesting is the
hierarchy.</li>
  <li><strong>How many?</strong> Optional <code class="language-plaintext highlighter-rouge">(0,1)</code>, zero or more <code class="language-plaintext highlighter-rouge">(0,n)</code>, or at least one <code class="language-plaintext highlighter-rouge">(1,n)</code>? Each
answer is a rule, and later a check.</li>
  <li><strong>Which excludes which?</strong> A transaction is a sale <em>or</em> a return, never both. Warnier
writes <code class="language-plaintext highlighter-rouge">⊕</code>; today we say <em>sum type</em>.</li>
  <li><strong>Logical or physical?</strong> The logical part is what the report says: the net total of
store S1 is 100.00. The physical part is how it is shown: page breaks, column widths,
JSON field names. Switch from a printed page to JSON, and only the physical part
changes. Keep them apart; the physical part lives at the edges.</li>
</ol>

<p>Each answer splits the problem into smaller parts, and each part gets its own type and
function. That is divide and conquer, guided by the data.</p>

<h2 id="six-passes-classic-and-modern-names">Six Passes, Classic and Modern Names</h2>

<p>The classic acronyms sound like 1970s mainframe jargon, because they are. Rename them
freely; the ideas survive. Each pass answers one question:</p>

<ol>
  <li><strong>Define the result</strong> (LOS, built with LFUD). What comes out, and how is it nested?</li>
  <li><strong>Derive the input</strong> (LIF). What must come in?</li>
  <li><strong>Design the process</strong> (LPS). What happens before, for each, and after?</li>
  <li><strong>Parse the input</strong> (LRR). How does untrusted data become valid input?</li>
  <li><strong>Format the output</strong> (PPR). How does the result look?</li>
  <li><strong>Verify.</strong> Where is each rule checked?</li>
</ol>

<p>The classic names: <em>Logical Output Structure</em> (LOS), built by <em>List, Frequency,
Universals, Draw</em> (LFUD), and called <em>Logical Output File</em> (LOF) by Warnier; <em>Logical
Input File</em> (LIF); <em>Logical Process Structure</em> (LPS); <em>Logical Read Routine</em> (LRR);
<em>Physical Put Routine</em> (PPR).</p>

<p>Each pass also has its place in the code:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>          inbound              core             outbound
          adapter                               adapter
input ──▶ 4. Parse ──▶ 1. Define the result ──▶ 5. Format ──▶ output
                       2. Derive the input
                       3. Design the process
          └────── 6. Verify: types, parser, tests ──────┘
</code></pre></div></div>

<p>To remember the modern names: three <strong>D</strong>s for the core, two adapters at the edges, one
check across all of them. The order is ours, not Hansen’s. He formats the output before
he parses the input; we parse first, because that is how the data flows.</p>

<h2 id="walkthrough-the-monthly-sales-report">Walkthrough: The Monthly Sales Report</h2>

<p>Let us take the ticket through all six passes, in Python 3.12+.</p>

<h3 id="pass-1-define-the-result">Pass 1: Define the Result</h3>

<p>First the sample output: not a class diagram, but the page that finance will read.</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>=== SALES REPORT 2026-11 ===

S1 Sofia Central
  T1  SALE      +120.00
  T2  RETURN     -20.00
  net total      100.00

S2 Plovdiv North
  (no transactions)
  net total        0.00

GRAND TOTAL      100.00
</code></pre></div></div>

<p>Then the bad case: what if some rows in the file are wrong? We could skip them and print
totals from the rest. But such a total looks correct and is not, and finance may trust
it. No total is safer than a wrong one. So if even one row is bad, the report prints no
totals. Instead, it lists <em>every</em> bad row, not only the first, so the user can fix the
whole file at once.</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>REJECTED: 3 bad row(s), no totals printed
  row 2: amount 'abc' is not a number
  row 3: unknown store 'S9'
  row 4: amount '-5.00' must be a positive number
</code></pre></div></div>

<p>Now LFUD. <strong>List</strong> the atoms, the smallest items on the samples: the period, the store
id and name, the amount, and the totals. Give the <strong>frequency</strong> of each by asking “once
per what?”: the grand total once per report, the net total once per store, the amount
once per transaction. The answers (report, store, transaction) are the <strong>universals</strong>:
the groups that the atoms belong to. Each universal becomes a bracket that holds its
atoms. Then <strong>draw</strong>, with exactly one place for each item:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>                        ┌ period
                        │
                        │        ┌ store id
                        │        │ name
                        │        │
                        │        │              ┌ Sale (0,1)
              ┌ Report ─┤ Store ─┤ Transaction ─┤   ⊕
              │ (0,1)   │ (1,n)  │ (0,n)        └ Return (0,1)
              │         │        │
Sales output ─┤         │        └ net total
              │         │
              │   ⊕     └ grand total
              │
              │                            ┌ row number
              └ Rejection ── Rejected row ─┤
                (0,1)        (1,n)         └ reason
</code></pre></div></div>

<p>A sales output is a report <em>or</em> a rejection. Errors are output too: someone reads the
rejection, just like the report, so it is designed in pass 1 with the same care, not
added later when the parser finds bad rows. The drawing also fixes two rules: one bad
row means no totals at all, and a rejection lists every bad row (1,n), not only the
first one.</p>

<p>Each bracket becomes a type, repetition becomes a tuple, and <code class="language-plaintext highlighter-rouge">⊕</code> becomes a union, named
with the <code class="language-plaintext highlighter-rouge">type</code> statement:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">dataclasses</span> <span class="kn">import</span> <span class="n">dataclass</span>
<span class="kn">from</span> <span class="nn">decimal</span> <span class="kn">import</span> <span class="n">Decimal</span>
<span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">ClassVar</span>

<span class="n">ZERO</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="s">"0.00"</span><span class="p">)</span>


<span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Sale</span><span class="p">:</span>
    <span class="n">tx_id</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">amount</span><span class="p">:</span> <span class="n">Decimal</span>  <span class="c1"># always &gt; 0; the kind decides the sign
</span>    <span class="n">label</span><span class="p">:</span> <span class="n">ClassVar</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="o">=</span> <span class="s">"SALE"</span>


<span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Return</span><span class="p">:</span>
    <span class="n">tx_id</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">amount</span><span class="p">:</span> <span class="n">Decimal</span>
    <span class="n">label</span><span class="p">:</span> <span class="n">ClassVar</span><span class="p">[</span><span class="nb">str</span><span class="p">]</span> <span class="o">=</span> <span class="s">"RETURN"</span>


<span class="nb">type</span> <span class="n">Transaction</span> <span class="o">=</span> <span class="n">Sale</span> <span class="o">|</span> <span class="n">Return</span>  <span class="c1"># ⊕: a sale or a return, never both
</span>

<span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">StoreSection</span><span class="p">:</span>
    <span class="n">store_id</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">transactions</span><span class="p">:</span> <span class="nb">tuple</span><span class="p">[</span><span class="n">Transaction</span><span class="p">,</span> <span class="p">...]</span>  <span class="c1"># (0,n): a quiet store is valid
</span>    <span class="n">net_total</span><span class="p">:</span> <span class="n">Decimal</span>


<span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Report</span><span class="p">:</span>
    <span class="n">period</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">stores</span><span class="p">:</span> <span class="nb">tuple</span><span class="p">[</span><span class="n">StoreSection</span><span class="p">,</span> <span class="p">...]</span>  <span class="c1"># (1,n)
</span>    <span class="n">grand_total</span><span class="p">:</span> <span class="n">Decimal</span>


<span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">RejectedRow</span><span class="p">:</span>
    <span class="n">number</span><span class="p">:</span> <span class="nb">int</span>
    <span class="n">reason</span><span class="p">:</span> <span class="nb">str</span>


<span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">Rejection</span><span class="p">:</span>
    <span class="n">rows</span><span class="p">:</span> <span class="nb">tuple</span><span class="p">[</span><span class="n">RejectedRow</span><span class="p">,</span> <span class="p">...]</span>  <span class="c1"># (1,n)
</span>

<span class="nb">type</span> <span class="n">SalesOutput</span> <span class="o">=</span> <span class="n">Report</span> <span class="o">|</span> <span class="n">Rejection</span>  <span class="c1"># ⊕: totals or reasons, never both
</span></code></pre></div></div>

<h3 id="pass-2-derive-the-input">Pass 2: Derive the Input</h3>

<p>Hansen’s rule for the ideal input: take the output and drop everything you can
calculate, plus fixed text such as titles. What remains is <em>required</em>. The hierarchy
stays the same:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">StoreInput</span><span class="p">:</span>
    <span class="n">store_id</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">name</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">transactions</span><span class="p">:</span> <span class="nb">tuple</span><span class="p">[</span><span class="n">Transaction</span><span class="p">,</span> <span class="p">...]</span>  <span class="c1"># (0,n)
</span>

<span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">SalesInput</span><span class="p">:</span>
    <span class="n">period</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">stores</span><span class="p">:</span> <span class="nb">tuple</span><span class="p">[</span><span class="n">StoreInput</span><span class="p">,</span> <span class="p">...]</span>  <span class="c1"># (1,n)
</span>
    <span class="k">def</span> <span class="nf">__post_init__</span><span class="p">(</span><span class="bp">self</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="bp">None</span><span class="p">:</span>
        <span class="k">if</span> <span class="ow">not</span> <span class="bp">self</span><span class="p">.</span><span class="n">stores</span><span class="p">:</span>  <span class="c1"># a broken setup, not bad data: fail fast
</span>            <span class="k">raise</span> <span class="nb">ValueError</span><span class="p">(</span><span class="s">"SalesInput needs at least one store (1,n)"</span><span class="p">)</span>
</code></pre></div></div>

<p>The totals are gone, because the program calculates them. <code class="language-plaintext highlighter-rouge">Sale</code> and <code class="language-plaintext highlighter-rouge">Return</code> have
nothing to calculate, so the input reuses them as they are.</p>

<p>The list of stores does not come from the CSV file. It comes from the <em>store master</em>
(<code class="language-plaintext highlighter-rouge">stores.csv</code> in the ticket), a setup list of all stores, so a store with no sales still
appears in the report. If that list is empty, the user’s file is not to blame; the
program was set up wrong. So we do not return a <code class="language-plaintext highlighter-rouge">Rejection</code>; we raise an error and stop
at once (<em>fail fast</em>).</p>

<p>The real file is not a tree like <code class="language-plaintext highlighter-rouge">SalesInput</code>. It is a flat list of CSV rows, all
strings. Turning those rows into <code class="language-plaintext highlighter-rouge">SalesInput</code> is the job of pass 4.</p>

<h3 id="pass-3-design-the-process">Pass 3: Design the Process</h3>

<p>Now add <strong>Begin</strong> and <strong>End</strong> to every repeating level: the title comes before the stores
(<em>Begin Report</em>), the grand total after them (<em>End Report</em>). Do not print yet. This pass
only computes the totals and builds the report as a value; pass 5 prints it. In code,
Begin, Process, End is often a fold:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">typing</span> <span class="kn">import</span> <span class="n">assert_never</span>


<span class="k">def</span> <span class="nf">signed</span><span class="p">(</span><span class="n">tx</span><span class="p">:</span> <span class="n">Transaction</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Decimal</span><span class="p">:</span>
    <span class="s">"""A sale adds to the total; a return takes away from it."""</span>
    <span class="n">match</span> <span class="n">tx</span><span class="p">:</span>
        <span class="n">case</span> <span class="n">Sale</span><span class="p">(</span><span class="n">amount</span><span class="o">=</span><span class="n">amount</span><span class="p">):</span>
            <span class="k">return</span> <span class="n">amount</span>
        <span class="n">case</span> <span class="n">Return</span><span class="p">(</span><span class="n">amount</span><span class="o">=</span><span class="n">amount</span><span class="p">):</span>
            <span class="k">return</span> <span class="o">-</span><span class="n">amount</span>
        <span class="n">case</span> <span class="n">_</span><span class="p">:</span>
            <span class="n">assert_never</span><span class="p">(</span><span class="n">tx</span><span class="p">)</span>


<span class="k">def</span> <span class="nf">build_store</span><span class="p">(</span><span class="n">store</span><span class="p">:</span> <span class="n">StoreInput</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">StoreSection</span><span class="p">:</span>
    <span class="n">net_total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">((</span><span class="n">signed</span><span class="p">(</span><span class="n">tx</span><span class="p">)</span> <span class="k">for</span> <span class="n">tx</span> <span class="ow">in</span> <span class="n">store</span><span class="p">.</span><span class="n">transactions</span><span class="p">),</span> <span class="n">ZERO</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">StoreSection</span><span class="p">(</span><span class="n">store</span><span class="p">.</span><span class="n">store_id</span><span class="p">,</span> <span class="n">store</span><span class="p">.</span><span class="n">name</span><span class="p">,</span> <span class="n">store</span><span class="p">.</span><span class="n">transactions</span><span class="p">,</span> <span class="n">net_total</span><span class="p">)</span>


<span class="k">def</span> <span class="nf">build_report</span><span class="p">(</span><span class="n">sales</span><span class="p">:</span> <span class="n">SalesInput</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Report</span><span class="p">:</span>
    <span class="n">stores</span> <span class="o">=</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">build_store</span><span class="p">(</span><span class="n">store</span><span class="p">)</span> <span class="k">for</span> <span class="n">store</span> <span class="ow">in</span> <span class="n">sales</span><span class="p">.</span><span class="n">stores</span><span class="p">)</span>
    <span class="n">grand_total</span> <span class="o">=</span> <span class="nb">sum</span><span class="p">((</span><span class="n">store</span><span class="p">.</span><span class="n">net_total</span> <span class="k">for</span> <span class="n">store</span> <span class="ow">in</span> <span class="n">stores</span><span class="p">),</span> <span class="n">ZERO</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">Report</span><span class="p">(</span><span class="n">sales</span><span class="p">.</span><span class="n">period</span><span class="p">,</span> <span class="n">stores</span><span class="p">,</span> <span class="n">grand_total</span><span class="p">)</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">sum(..., ZERO)</code> is the pattern in one line: <code class="language-plaintext highlighter-rouge">ZERO</code> is Begin, adding each amount is
Process, the result is End. The <code class="language-plaintext highlighter-rouge">match</code> in <code class="language-plaintext highlighter-rouge">signed</code> is exhaustive: it covers every case of
<code class="language-plaintext highlighter-rouge">Transaction</code>, the <code class="language-plaintext highlighter-rouge">⊕</code> from the diagram, and the last case makes a type checker prove it.
When every kind is covered, nothing is left for <code class="language-plaintext highlighter-rouge">case _</code>, and <code class="language-plaintext highlighter-rouge">assert_never</code> accepts only
that: nothing (the type <code class="language-plaintext highlighter-rouge">Never</code>). Add a third kind to the union, and the checker reports
that it reaches <code class="language-plaintext highlighter-rouge">assert_never</code>. End every <code class="language-plaintext highlighter-rouge">match</code> over a <code class="language-plaintext highlighter-rouge">⊕</code> this way. Without it, a loop
or a generator that misses a case gives no error at all; it just skips the item. The core
is done: one pure function per bracket, no I/O.</p>

<h3 id="pass-4-parse-the-input">Pass 4: Parse the Input</h3>

<p>Hansen calls this the brick-wall rule: “build a brick wall around your output; then you
only worry about calculations inside the wall”. All contact with the outside world goes
through the read routine, which today we call an inbound adapter. The rule has a modern
name too, <em>parse, don’t validate</em>: turn a raw row into a type that cannot be wrong.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">from</span> <span class="nn">collections.abc</span> <span class="kn">import</span> <span class="n">Iterable</span>
<span class="kn">from</span> <span class="nn">decimal</span> <span class="kn">import</span> <span class="n">InvalidOperation</span>

<span class="n">KINDS</span> <span class="o">=</span> <span class="p">{</span><span class="n">kind</span><span class="p">.</span><span class="n">label</span><span class="p">:</span> <span class="n">kind</span> <span class="k">for</span> <span class="n">kind</span> <span class="ow">in</span> <span class="p">(</span><span class="n">Sale</span><span class="p">,</span> <span class="n">Return</span><span class="p">)}</span>  <span class="c1"># {"SALE": Sale, "RETURN": Return}
</span>

<span class="k">class</span> <span class="nc">RowError</span><span class="p">(</span><span class="nb">ValueError</span><span class="p">):</span>
    <span class="s">"""One raw row that cannot become a Transaction."""</span>


<span class="k">def</span> <span class="nf">read_input</span><span class="p">(</span>
    <span class="n">period</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">stores</span><span class="p">:</span> <span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">str</span><span class="p">],</span> <span class="n">rows</span><span class="p">:</span> <span class="n">Iterable</span><span class="p">[</span><span class="nb">list</span><span class="p">[</span><span class="nb">str</span><span class="p">]]</span>
<span class="p">)</span> <span class="o">-&gt;</span> <span class="n">SalesInput</span> <span class="o">|</span> <span class="n">Rejection</span><span class="p">:</span>
    <span class="s">"""Raw CSV rows in; valid input, or every reason why not, out."""</span>
    <span class="n">grouped</span><span class="p">:</span> <span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">list</span><span class="p">[</span><span class="n">Transaction</span><span class="p">]]</span> <span class="o">=</span> <span class="p">{</span><span class="n">store_id</span><span class="p">:</span> <span class="p">[]</span> <span class="k">for</span> <span class="n">store_id</span> <span class="ow">in</span> <span class="n">stores</span><span class="p">}</span>
    <span class="n">rejected</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="n">RejectedRow</span><span class="p">]</span> <span class="o">=</span> <span class="p">[]</span>
    <span class="k">for</span> <span class="n">number</span><span class="p">,</span> <span class="n">fields</span> <span class="ow">in</span> <span class="nb">enumerate</span><span class="p">(</span><span class="n">rows</span><span class="p">,</span> <span class="n">start</span><span class="o">=</span><span class="mi">1</span><span class="p">):</span>
        <span class="k">try</span><span class="p">:</span>
            <span class="n">store_id</span><span class="p">,</span> <span class="n">tx</span> <span class="o">=</span> <span class="n">parse_row</span><span class="p">(</span><span class="n">fields</span><span class="p">,</span> <span class="n">stores</span><span class="p">)</span>
        <span class="k">except</span> <span class="n">RowError</span> <span class="k">as</span> <span class="n">error</span><span class="p">:</span>
            <span class="n">rejected</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="n">RejectedRow</span><span class="p">(</span><span class="n">number</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">error</span><span class="p">)))</span>
            <span class="k">continue</span>
        <span class="n">grouped</span><span class="p">[</span><span class="n">store_id</span><span class="p">].</span><span class="n">append</span><span class="p">(</span><span class="n">tx</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">rejected</span><span class="p">:</span>
        <span class="k">return</span> <span class="n">Rejection</span><span class="p">(</span><span class="nb">tuple</span><span class="p">(</span><span class="n">rejected</span><span class="p">))</span>
    <span class="k">return</span> <span class="n">SalesInput</span><span class="p">(</span><span class="n">period</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">(</span>
        <span class="n">StoreInput</span><span class="p">(</span><span class="n">store_id</span><span class="p">,</span> <span class="n">name</span><span class="p">,</span> <span class="nb">tuple</span><span class="p">(</span><span class="n">grouped</span><span class="p">[</span><span class="n">store_id</span><span class="p">]))</span> <span class="k">for</span> <span class="n">store_id</span><span class="p">,</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">stores</span><span class="p">.</span><span class="n">items</span><span class="p">()</span>
    <span class="p">))</span>


<span class="k">def</span> <span class="nf">parse_row</span><span class="p">(</span><span class="n">fields</span><span class="p">:</span> <span class="nb">list</span><span class="p">[</span><span class="nb">str</span><span class="p">],</span> <span class="n">stores</span><span class="p">:</span> <span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">str</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="nb">tuple</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="n">Transaction</span><span class="p">]:</span>
    <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">fields</span><span class="p">)</span> <span class="o">!=</span> <span class="mi">4</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">RowError</span><span class="p">(</span><span class="sa">f</span><span class="s">"expected 4 fields, got </span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">fields</span><span class="p">)</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
    <span class="n">tx_id</span><span class="p">,</span> <span class="n">store_id</span><span class="p">,</span> <span class="n">kind</span><span class="p">,</span> <span class="n">amount</span> <span class="o">=</span> <span class="p">(</span><span class="n">field</span><span class="p">.</span><span class="n">strip</span><span class="p">()</span> <span class="k">for</span> <span class="n">field</span> <span class="ow">in</span> <span class="n">fields</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">store_id</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">stores</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">RowError</span><span class="p">(</span><span class="sa">f</span><span class="s">"unknown store </span><span class="si">{</span><span class="n">store_id</span><span class="si">!r}</span><span class="s">"</span><span class="p">)</span>
    <span class="k">if</span> <span class="n">kind</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">KINDS</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">RowError</span><span class="p">(</span><span class="sa">f</span><span class="s">"unknown kind </span><span class="si">{</span><span class="n">kind</span><span class="si">!r}</span><span class="s">"</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">store_id</span><span class="p">,</span> <span class="n">KINDS</span><span class="p">[</span><span class="n">kind</span><span class="p">](</span><span class="n">tx_id</span><span class="p">,</span> <span class="n">parse_amount</span><span class="p">(</span><span class="n">amount</span><span class="p">))</span>


<span class="k">def</span> <span class="nf">parse_amount</span><span class="p">(</span><span class="n">text</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="n">Decimal</span><span class="p">:</span>
    <span class="k">try</span><span class="p">:</span>
        <span class="n">amount</span> <span class="o">=</span> <span class="n">Decimal</span><span class="p">(</span><span class="n">text</span><span class="p">)</span>
    <span class="k">except</span> <span class="n">InvalidOperation</span><span class="p">:</span>
        <span class="k">raise</span> <span class="n">RowError</span><span class="p">(</span><span class="sa">f</span><span class="s">"amount </span><span class="si">{</span><span class="n">text</span><span class="si">!r}</span><span class="s"> is not a number"</span><span class="p">)</span> <span class="k">from</span> <span class="bp">None</span>
    <span class="k">if</span> <span class="ow">not</span> <span class="n">amount</span><span class="p">.</span><span class="n">is_finite</span><span class="p">()</span> <span class="ow">or</span> <span class="n">amount</span> <span class="o">&lt;=</span> <span class="mi">0</span><span class="p">:</span>  <span class="c1"># Decimal accepts "NaN" and "Infinity"
</span>        <span class="k">raise</span> <span class="n">RowError</span><span class="p">(</span><span class="sa">f</span><span class="s">"amount </span><span class="si">{</span><span class="n">text</span><span class="si">!r}</span><span class="s"> must be a positive number"</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">amount</span>
</code></pre></div></div>

<p>Three choices are deliberate. Every row is parsed, so the user fixes the whole file in
one round. Each error carries its row number. And bad rows are expected, so they come
back as a value, <code class="language-plaintext highlighter-rouge">SalesInput | Rejection</code>; <code class="language-plaintext highlighter-rouge">RowError</code> never leaves this adapter. The
store master (<code class="language-plaintext highlighter-rouge">{id: name}</code>) drives the grouping, which is how the quiet store <code class="language-plaintext highlighter-rouge">S2</code>
reaches the report.</p>

<h3 id="pass-5-format-the-output">Pass 5: Format the Output</h3>

<p>The physical output walks the same tree, and <code class="language-plaintext highlighter-rouge">match</code> makes the top-level <code class="language-plaintext highlighter-rouge">⊕</code> explicit:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">format_output</span><span class="p">(</span><span class="n">output</span><span class="p">:</span> <span class="n">SalesOutput</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="n">match</span> <span class="n">output</span><span class="p">:</span>
        <span class="n">case</span> <span class="n">Rejection</span><span class="p">(</span><span class="n">rows</span><span class="o">=</span><span class="n">rows</span><span class="p">):</span>
            <span class="n">lines</span> <span class="o">=</span> <span class="p">[</span><span class="sa">f</span><span class="s">"REJECTED: </span><span class="si">{</span><span class="nb">len</span><span class="p">(</span><span class="n">rows</span><span class="p">)</span><span class="si">}</span><span class="s"> bad row(s), no totals printed"</span><span class="p">]</span>
            <span class="n">lines</span> <span class="o">+=</span> <span class="p">[</span><span class="sa">f</span><span class="s">"  row </span><span class="si">{</span><span class="n">bad</span><span class="p">.</span><span class="n">number</span><span class="si">}</span><span class="s">: </span><span class="si">{</span><span class="n">bad</span><span class="p">.</span><span class="n">reason</span><span class="si">}</span><span class="s">"</span> <span class="k">for</span> <span class="n">bad</span> <span class="ow">in</span> <span class="n">rows</span><span class="p">]</span>
        <span class="n">case</span> <span class="n">Report</span><span class="p">():</span>
            <span class="n">lines</span> <span class="o">=</span> <span class="p">[</span><span class="sa">f</span><span class="s">"=== SALES REPORT </span><span class="si">{</span><span class="n">output</span><span class="p">.</span><span class="n">period</span><span class="si">}</span><span class="s"> ==="</span><span class="p">]</span>  <span class="c1"># Begin Report
</span>            <span class="k">for</span> <span class="n">store</span> <span class="ow">in</span> <span class="n">output</span><span class="p">.</span><span class="n">stores</span><span class="p">:</span>  <span class="c1"># Store (1,n)
</span>                <span class="n">lines</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="sa">f</span><span class="s">"</span><span class="se">\n</span><span class="si">{</span><span class="n">store</span><span class="p">.</span><span class="n">store_id</span><span class="si">}</span><span class="s"> </span><span class="si">{</span><span class="n">store</span><span class="p">.</span><span class="n">name</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>  <span class="c1"># Begin Store
</span>                <span class="k">if</span> <span class="ow">not</span> <span class="n">store</span><span class="p">.</span><span class="n">transactions</span><span class="p">:</span>
                    <span class="n">lines</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="s">"  (no transactions)"</span><span class="p">)</span>
                <span class="k">for</span> <span class="n">tx</span> <span class="ow">in</span> <span class="n">store</span><span class="p">.</span><span class="n">transactions</span><span class="p">:</span>  <span class="c1"># Transaction (0,n)
</span>                    <span class="n">lines</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="sa">f</span><span class="s">"  </span><span class="si">{</span><span class="n">tx</span><span class="p">.</span><span class="n">tx_id</span><span class="si">:</span><span class="o">&lt;</span><span class="mi">4</span><span class="si">}{</span><span class="n">tx</span><span class="p">.</span><span class="n">label</span><span class="si">:</span><span class="o">&lt;</span><span class="mi">8</span><span class="si">}{</span><span class="n">signed</span><span class="p">(</span><span class="n">tx</span><span class="p">)</span><span class="si">:</span><span class="o">&gt;+</span><span class="mf">9.2</span><span class="n">f</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>
                <span class="n">lines</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="sa">f</span><span class="s">"  net total   </span><span class="si">{</span><span class="n">store</span><span class="p">.</span><span class="n">net_total</span><span class="si">:</span><span class="o">&gt;</span><span class="mf">9.2</span><span class="n">f</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>  <span class="c1"># End Store
</span>            <span class="n">lines</span><span class="p">.</span><span class="n">append</span><span class="p">(</span><span class="sa">f</span><span class="s">"</span><span class="se">\n</span><span class="s">GRAND TOTAL   </span><span class="si">{</span><span class="n">output</span><span class="p">.</span><span class="n">grand_total</span><span class="si">:</span><span class="o">&gt;</span><span class="mf">9.2</span><span class="n">f</span><span class="si">}</span><span class="s">"</span><span class="p">)</span>  <span class="c1"># End Report
</span>        <span class="n">case</span> <span class="n">_</span><span class="p">:</span>
            <span class="n">assert_never</span><span class="p">(</span><span class="n">output</span><span class="p">)</span>
    <span class="k">return</span> <span class="s">"</span><span class="se">\n</span><span class="s">"</span><span class="p">.</span><span class="n">join</span><span class="p">(</span><span class="n">lines</span><span class="p">)</span>
</code></pre></div></div>

<p>Pages, CSV, JSON, or HTML belong here; the core does not change. The wiring is one more
<code class="language-plaintext highlighter-rouge">match</code>, over the result of <code class="language-plaintext highlighter-rouge">read_input</code>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">csv</span>
<span class="kn">import</span> <span class="nn">sys</span>
<span class="kn">from</span> <span class="nn">pathlib</span> <span class="kn">import</span> <span class="n">Path</span>


<span class="k">def</span> <span class="nf">run</span><span class="p">(</span><span class="n">period</span><span class="p">:</span> <span class="nb">str</span><span class="p">,</span> <span class="n">stores</span><span class="p">:</span> <span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="nb">str</span><span class="p">],</span> <span class="n">raw_csv</span><span class="p">:</span> <span class="nb">str</span><span class="p">)</span> <span class="o">-&gt;</span> <span class="nb">str</span><span class="p">:</span>
    <span class="n">parsed</span> <span class="o">=</span> <span class="n">read_input</span><span class="p">(</span><span class="n">period</span><span class="p">,</span> <span class="n">stores</span><span class="p">,</span> <span class="n">csv</span><span class="p">.</span><span class="n">reader</span><span class="p">(</span><span class="n">raw_csv</span><span class="p">.</span><span class="n">splitlines</span><span class="p">()))</span>
    <span class="n">match</span> <span class="n">parsed</span><span class="p">:</span>
        <span class="n">case</span> <span class="n">Rejection</span><span class="p">():</span>
            <span class="k">return</span> <span class="n">format_output</span><span class="p">(</span><span class="n">parsed</span><span class="p">)</span>
        <span class="n">case</span> <span class="n">SalesInput</span><span class="p">():</span>
            <span class="k">return</span> <span class="n">format_output</span><span class="p">(</span><span class="n">build_report</span><span class="p">(</span><span class="n">parsed</span><span class="p">))</span>
        <span class="n">case</span> <span class="n">_</span><span class="p">:</span>
            <span class="n">assert_never</span><span class="p">(</span><span class="n">parsed</span><span class="p">)</span>


<span class="k">def</span> <span class="nf">main</span><span class="p">()</span> <span class="o">-&gt;</span> <span class="bp">None</span><span class="p">:</span>
    <span class="s">"""sales-report 2026-11 stores.csv sales.csv"""</span>
    <span class="n">period</span><span class="p">,</span> <span class="n">stores_file</span><span class="p">,</span> <span class="n">sales_file</span> <span class="o">=</span> <span class="n">sys</span><span class="p">.</span><span class="n">argv</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
    <span class="n">store_rows</span> <span class="o">=</span> <span class="n">Path</span><span class="p">(</span><span class="n">stores_file</span><span class="p">).</span><span class="n">read_text</span><span class="p">().</span><span class="n">splitlines</span><span class="p">()</span>  <span class="c1"># "S1,Sofia Central"
</span>    <span class="n">stores</span> <span class="o">=</span> <span class="nb">dict</span><span class="p">(</span><span class="n">csv</span><span class="p">.</span><span class="n">reader</span><span class="p">(</span><span class="n">store_rows</span><span class="p">))</span>
    <span class="k">print</span><span class="p">(</span><span class="n">run</span><span class="p">(</span><span class="n">period</span><span class="p">,</span> <span class="n">stores</span><span class="p">,</span> <span class="n">Path</span><span class="p">(</span><span class="n">sales_file</span><span class="p">).</span><span class="n">read_text</span><span class="p">()))</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">main</code> only reads files and prints. <code class="language-plaintext highlighter-rouge">run</code> takes plain strings, so tests can call it
without files.</p>

<p>Scott Wlaschin’s [railway-oriented programming][rop] fits here too: each <code class="language-plaintext highlighter-rouge">case</code> is a
track, success or failure, and both tracks end in <code class="language-plaintext highlighter-rouge">format_output</code>.</p>

<h3 id="pass-6-verify">Pass 6: Verify</h3>

<p>Every mark in the diagram is a rule, and every rule needs a place where it is checked.
The language construct you choose for a mark decides how early that check happens:</p>

<table>
  <thead>
    <tr>
      <th>Mark</th>
      <th>Python</th>
      <th>Other languages</th>
      <th>Checked by</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Sequence</td>
      <td>frozen <code class="language-plaintext highlighter-rouge">dataclass</code></td>
      <td>record, struct</td>
      <td>type checker</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">(0,1)</code></td>
      <td><code>X &#124; None</code></td>
      <td><code class="language-plaintext highlighter-rouge">Option</code>, nullable type</td>
      <td>type checker</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">(0,n)</code></td>
      <td><code class="language-plaintext highlighter-rouge">tuple[X, ...]</code></td>
      <td>list</td>
      <td>type checker</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">(1,n)</code></td>
      <td><code class="language-plaintext highlighter-rouge">tuple</code> + check in <code class="language-plaintext highlighter-rouge">__post_init__</code></td>
      <td>non-empty list, or a constructor check</td>
      <td>constructor, at run time</td>
    </tr>
    <tr>
      <td><code class="language-plaintext highlighter-rouge">⊕</code></td>
      <td><code>type T = A &#124; B</code> + <code class="language-plaintext highlighter-rouge">match</code> ending in <code class="language-plaintext highlighter-rouge">assert_never</code></td>
      <td>sum type, sealed class</td>
      <td>type checker</td>
    </tr>
    <tr>
      <td>Value rule</td>
      <td>parse function</td>
      <td>parse function, value type</td>
      <td>parser, at the boundary</td>
    </tr>
    <tr>
      <td>Page layout</td>
      <td>—</td>
      <td>—</td>
      <td>golden test</td>
    </tr>
  </tbody>
</table>

<p>The rows run from the earliest check to the latest. In the sales report, the type checker
covers the brackets and both <code class="language-plaintext highlighter-rouge">⊕</code>. <code class="language-plaintext highlighter-rouge">SalesInput.__post_init__</code> checks that there is at
least one store, <code class="language-plaintext highlighter-rouge">parse_amount</code> checks that an amount is positive, and the golden test
below checks the page.</p>

<p>Two kinds of failure: bad data is expected, so collect it and report it as output; a
broken invariant in the core is a bug, so fail fast.</p>

<p>These checks cover the rules one by one. The samples from pass 1 check that the parts work
together. We wrote them by hand, before any code. Now we feed in the input that should
produce them, run the whole program, and compare the full text:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">STORES</span> <span class="o">=</span> <span class="p">{</span><span class="s">"S1"</span><span class="p">:</span> <span class="s">"Sofia Central"</span><span class="p">,</span> <span class="s">"S2"</span><span class="p">:</span> <span class="s">"Plovdiv North"</span><span class="p">}</span>

<span class="n">GOOD_CSV</span> <span class="o">=</span> <span class="s">"""</span><span class="se">\
</span><span class="s">T1,S1,SALE,120.00
T2,S1,RETURN,20.00
"""</span>

<span class="n">BAD_CSV</span> <span class="o">=</span> <span class="s">"""</span><span class="se">\
</span><span class="s">T1,S1,SALE,120.00
T2,S1,SALE,abc
T3,S9,SALE,10.00
T4,S1,RETURN,-5.00
"""</span>

<span class="k">assert</span> <span class="n">run</span><span class="p">(</span><span class="s">"2026-11"</span><span class="p">,</span> <span class="n">STORES</span><span class="p">,</span> <span class="n">GOOD_CSV</span><span class="p">)</span> <span class="o">==</span> <span class="n">SAMPLE_REPORT</span>
<span class="k">assert</span> <span class="n">run</span><span class="p">(</span><span class="s">"2026-11"</span><span class="p">,</span> <span class="n">STORES</span><span class="p">,</span> <span class="n">BAD_CSV</span><span class="p">)</span> <span class="o">==</span> <span class="n">SAMPLE_REJECTION</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">SAMPLE_REPORT</code> and <code class="language-plaintext highlighter-rouge">SAMPLE_REJECTION</code> are the two texts from pass 1, copied as they are.
A test that compares the whole output with a saved text is a <em>golden test</em>. The first run
may fail because the hand-made sample is wrong: a column too narrow, a typo. Fix whichever
side is wrong, the code or the sample. After that the sample is frozen, and any change to
the report breaks the test. Two examples do not prove that the design is correct, but
they close the loop: the page you wrote first is the page you check last.</p>

<h2 id="divide-and-conquer-when-structures-clash">Divide and Conquer: When Structures Clash</h2>

<p>Sometimes two structures do not line up, and one loop cannot follow both. Jackson called
this a <em>structure clash</em>. Hansen follows his advice: do not force one loop to serve two
trees. <strong>Use two programs joined by a stream, one per structure</strong>. Jackson named three
kinds of clash: boundary, ordering, and interleaving. His ordering clash hides two needs,
grouping and sorting, so this post splits it in two. Each kind needs its own information
in the stream, and each has its own cost.</p>

<h3 id="boundary-clash">Boundary Clash</h3>

<p>A report is stores and transactions, but paper is pages, and a store may start on one
page and end on the next. In Python, the two programs become a generator pipeline:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">pages</span> <span class="o">=</span> <span class="n">paginate</span><span class="p">(</span><span class="n">lines_of</span><span class="p">(</span><span class="n">report</span><span class="p">),</span> <span class="n">lines_per_page</span><span class="o">=</span><span class="mi">54</span><span class="p">)</span>  <span class="c1"># a sketch
</span></code></pre></div></div>

<p>The stream needs more than text. When <code class="language-plaintext highlighter-rouge">lines_of</code> flattens the report into lines, the
store boundaries are lost, but some page rules still need them. If a store goes on to the
next page, that page should start with <code class="language-plaintext highlighter-rouge">S1 Sofia Central (continued)</code>. From plain text,
<code class="language-plaintext highlighter-rouge">paginate</code> cannot know which store it is in. So the first program adds meta information
to the stream: each line carries its store.</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">dataclass</span><span class="p">(</span><span class="n">frozen</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
<span class="k">class</span> <span class="nc">ReportLine</span><span class="p">:</span>
    <span class="n">text</span><span class="p">:</span> <span class="nb">str</span>
    <span class="n">store</span><span class="p">:</span> <span class="nb">str</span> <span class="o">|</span> <span class="bp">None</span>  <span class="c1"># meta: "S1 Sofia Central", or None outside a store
</span></code></pre></div></div>

<p>Find the meta information the same way as everything else: from the output. List the
rules of the second tree. Every rule that names a part of the first tree becomes a marker
or a field in the stream. Put it in the stream, not in the domain types: <code class="language-plaintext highlighter-rouge">StoreSection</code>
does not change.</p>

<p>The two programs are different kinds of function. The first flattens a tree into a
stream, and that is a <em>bind</em>: each node becomes its own lines, and the results are joined
in order. Here each store becomes its lines. In Python that is <code class="language-plaintext highlighter-rouge">yield from</code>; in other
languages it is often called <code class="language-plaintext highlighter-rouge">flatMap</code>. <code class="language-plaintext highlighter-rouge">paginate</code> cannot be a bind. Bind breaks one node
into lines, but it never puts lines of different nodes into one group, and that is
exactly what a page does. <code class="language-plaintext highlighter-rouge">paginate</code> needs state, the lines already on the page, so it is
an <em>unfold</em>. In Python, a generator with a local variable keeps that state.</p>

<p>So the whole pipeline has two steps: flatten one tree into a stream, then build the other
tree from that stream. The two steps run together, not one after the other. <code class="language-plaintext highlighter-rouge">paginate</code>
asks for the next line only when it needs one, so the first page is ready before the
whole report is flattened. Jackson called this <em>program inversion</em>: one program becomes
a subroutine that the other calls for each item, and it keeps its place between calls.
A Python generator works this way, with no extra library.</p>

<p>Each <code class="language-plaintext highlighter-rouge">next()</code> goes down the pipeline, and one line comes back up:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>caller        paginate          lines_of          a store
  │ next() ────►│                 │                 │
  │             │ next() ────────►│ yield from ────►│
  │             │◄───────────── a line ─────────────│  lines_of and a store pause
  │             │ ... until the page is full
  │◄─── Page ───│
</code></pre></div></div>

<p>Each generator on the path pauses at its <code class="language-plaintext highlighter-rouge">yield</code> and keeps its local variables. The next
call resumes it there. The total work does not change; only its order does. But the
first page now costs only the work for one page, whatever the size of the input. A
pipeline that builds a full list at each step must process the whole input before it
can return page 1.</p>

<p>The companion project <code class="language-plaintext highlighter-rouge">PrintersDevil</code> does this at full scale: a text formatter from
Charles Wetherell’s <a href="https://www.amazon.com/Etudes-Programmers-Charles-Wetherell/dp/0132918072"><em>Etudes for Programmers</em></a>, where paragraphs clash
with pages. Its line stream carries two markers next to the text: <code class="language-plaintext highlighter-rouge">GapLine</code>, the space
before a paragraph, dropped at the top of a page, and <code class="language-plaintext highlighter-rouge">PageBreak</code>, which can change the
page height.</p>

<h3 id="grouping-and-ordering-clashes">Grouping and Ordering Clashes</h3>

<p>You have already met one, in pass 4. The CSV file lists the rows as they were recorded,
with all stores mixed. The report needs them store by store, in the order of the store
master. Nothing in the file marks the end of a store: the last row of the file may still
belong to the first store. So no store is complete before the whole file is read.</p>

<p>Jackson called this an ordering clash. His files were sequential, and the usual way to
bring the rows of one store together was to sort the file. With a dict in memory, these
are two different needs:</p>

<ul>
  <li><strong>Grouping:</strong> the items of one group are scattered, and the stream carries a group
key. <code class="language-plaintext highlighter-rouge">read_input</code> starts one empty list per store from the store master, and puts each
row into the list of its store. Nothing is sorted: the store master gives the order of
the stores, and the file gives the order inside each store.</li>
  <li><strong>Ordering:</strong> the groups, or the items inside a group, must follow a value in the
data: an id, a date, a total. The stream carries a sort key. If finance wanted the
stores by name, the report would need a sort; as it is, it does not.</li>
</ul>

<p>A sort by the group key does both at once. In Python, that is <code class="language-plaintext highlighter-rouge">sorted</code> followed by
<code class="language-plaintext highlighter-rouge">itertools.groupby</code>, which joins only neighbours. It is also the way out when the groups
do not fit in memory: sort outside the program, with an external sort or with <code class="language-plaintext highlighter-rouge">ORDER BY</code>
in the database, and each store arrives in one piece.</p>

<p>The cost is waiting. The two programs cannot run together; the grouping stands between
them. A month of sales fits in memory, so a dict is enough.</p>

<h3 id="interleaving-clash">Interleaving Clash</h3>

<p>A server log holds the lines of many user sessions, mixed as they happen. This time each
group marks its own end. A session has its own structure: a login, (0,n) actions, and a
logout. That is Begin, Process, and End from pass 3, but many sessions are open at the
same time. A session is complete at its logout, long before the log ends, so its summary
can come out at once. The summaries come out in the order the sessions end, not in the
order of a key.</p>

<p>Jackson’s answer is one small program per session, paused between its lines. In Python,
a dict keeps the state of each open session, and the session id in every line is the
group key:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="o">@</span><span class="n">dataclass</span>
<span class="k">class</span> <span class="nc">OpenSession</span><span class="p">:</span>
    <span class="n">started</span><span class="p">:</span> <span class="n">datetime</span>
    <span class="n">actions</span><span class="p">:</span> <span class="nb">int</span> <span class="o">=</span> <span class="mi">0</span>


<span class="k">def</span> <span class="nf">session_summaries</span><span class="p">(</span><span class="n">log</span><span class="p">:</span> <span class="n">Iterable</span><span class="p">[</span><span class="n">LogLine</span><span class="p">])</span> <span class="o">-&gt;</span> <span class="n">Iterator</span><span class="p">[</span><span class="n">SessionSummary</span><span class="p">]:</span>  <span class="c1"># a sketch
</span>    <span class="n">open_sessions</span><span class="p">:</span> <span class="nb">dict</span><span class="p">[</span><span class="nb">str</span><span class="p">,</span> <span class="n">OpenSession</span><span class="p">]</span> <span class="o">=</span> <span class="p">{}</span>
    <span class="k">for</span> <span class="n">line</span> <span class="ow">in</span> <span class="n">log</span><span class="p">:</span>
        <span class="n">match</span> <span class="n">line</span><span class="p">:</span>
            <span class="n">case</span> <span class="n">Login</span><span class="p">(</span><span class="n">session_id</span><span class="o">=</span><span class="n">sid</span><span class="p">,</span> <span class="n">at</span><span class="o">=</span><span class="n">at</span><span class="p">):</span>  <span class="c1"># Begin
</span>                <span class="n">open_sessions</span><span class="p">[</span><span class="n">sid</span><span class="p">]</span> <span class="o">=</span> <span class="n">OpenSession</span><span class="p">(</span><span class="n">started</span><span class="o">=</span><span class="n">at</span><span class="p">)</span>
            <span class="n">case</span> <span class="n">Action</span><span class="p">(</span><span class="n">session_id</span><span class="o">=</span><span class="n">sid</span><span class="p">):</span>  <span class="c1"># Process
</span>                <span class="n">open_sessions</span><span class="p">[</span><span class="n">sid</span><span class="p">].</span><span class="n">actions</span> <span class="o">+=</span> <span class="mi">1</span>
            <span class="n">case</span> <span class="n">Logout</span><span class="p">(</span><span class="n">session_id</span><span class="o">=</span><span class="n">sid</span><span class="p">,</span> <span class="n">at</span><span class="o">=</span><span class="n">at</span><span class="p">):</span>  <span class="c1"># End
</span>                <span class="n">session</span> <span class="o">=</span> <span class="n">open_sessions</span><span class="p">.</span><span class="n">pop</span><span class="p">(</span><span class="n">sid</span><span class="p">)</span>
                <span class="k">yield</span> <span class="n">SessionSummary</span><span class="p">(</span><span class="n">sid</span><span class="p">,</span> <span class="n">session</span><span class="p">.</span><span class="n">started</span><span class="p">,</span> <span class="n">at</span><span class="p">,</span> <span class="n">session</span><span class="p">.</span><span class="n">actions</span><span class="p">)</span>
            <span class="n">case</span> <span class="n">_</span><span class="p">:</span>
                <span class="n">assert_never</span><span class="p">(</span><span class="n">line</span><span class="p">)</span>
</code></pre></div></div>

<p>The two programs run together again, but now you must know how each group ends. Logout
is the easy case. A user who closes the browser never logs out, so the program needs a
timeout. And when the log stops, some sessions are still open: report them as
incomplete, or drop them on purpose. Without such rules, the dict only grows.</p>

<h3 id="which-clash-is-it">Which Clash Is It?</h3>

<p>Here is a simple test. When you turn one structure into another, try to write the step
as a <em>bind</em>. If you can, the structures fit. If you cannot, because an output group needs
items from more than one input node, the structures clash, and the step needs its own
program. Then look at the output group:</p>

<ul>
  <li>It cuts across the input groups, like a page that holds the end of one store and the
start of the next: a <strong>boundary clash</strong>. The stream carries markers.</li>
  <li>Its items are scattered, and nothing marks where it ends, like the rows of one store in
the sales file: a <strong>grouping clash</strong>. The stream carries a group key.</li>
  <li>It must follow a value in the data that the input does not follow, like customers by
id: an <strong>ordering clash</strong>. The stream carries a sort key.</li>
  <li>It collects its items while other groups are still open, like the lines of one session
between login and logout: an <strong>interleaving clash</strong>. The stream carries a group key.</li>
</ul>

<p>Grouping and interleaving look alike: in both, items of many groups come mixed. One
question tells them apart: can a group be finished before the input ends?</p>

<ul>
  <li>No. Nothing marks the end of a group, so you read the whole input and put each item
into the bucket of its key. That is a grouping clash, like the sales file.</li>
  <li>Yes. Each group has its own Begin and End, so it comes out as soon as it ends, and the
groups come out in the order they end. That is an interleaving clash, like the
sessions.</li>
</ul>

<p>The border is also a design choice. Any interleaving clash can be solved as a grouping
clash: read the whole log, then group it by session id. Do that when you can wait for the
end of the input. A session report sorted by user also has an ordering clash, even with
logout lines, and one sort by user and session solves both. Keep one state per open
group only when you cannot wait: the log never stops, or each summary is needed as soon
as its session ends.</p>

<h2 id="a-way-of-thinking-not-a-new-method">A Way of Thinking, Not a New Method</h2>

<p>Nothing in this post is new. Warnier/Orr is not a framework, and you do not need its
diagrams. It is a way of thinking at the level of logical construction: before you write
code, decide what comes out, how it is nested, how many of each part there are, and which
part excludes which. The types, the functions, and the checks follow from the answers.</p>

<p>The construction needs names, and the programmer does not invent them. They come from the
domain, and DDD is how we find them: the bounded context and its ubiquitous language.
Report, store, transaction, sale, and return are words that finance uses. The same words
name the levels of the diagram, the types in the core, and the functions that build them.</p>

<p>The same line of reasoning runs through the whole hexagon. It starts at the output and
works back to the input; the data later flows the other way. The numbers are the passes:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>┌─ Bounded context: report, store, transaction, sale, return ──┐
│  reasoning: from the output back to the input                │
│  ◄─────────────────────────────────────────────────────────  │
│                                                              │
│  inbound          core                         outbound      │
│  adapter                                       adapter       │
│  (physical)       (logical)                    (physical)    │
│  ┌──────────┐     ┌──────────────────────┐     ┌──────────┐  │
│  │ CSV rows │ ──► │ SalesInput ─► Report │ ──► │ page     │  │
│  │ parse  4 │     │ 2           3      1 │     │ format 5 │  │
│  └──────────┘     └──────────────────────┘     └──────────┘  │
│                                                              │
│  ─────────────────────────────────────────────────────────►  │
│  data: from the input to the output                          │
└──────────────────────────────────────────────────────────────┘
</code></pre></div></div>

<p>The core holds the logical structures, named in domain words. The adapters hold the
physical ones: CSV rows on one side, the printed page on the other. They are structures
too, and the same questions apply: how is it nested, how many, which excludes which.
Where a physical structure differs from the logical one, the adapter translates. Where
the two do not line up at all, it is a structure clash, and it takes two programs joined
by a stream. Pass 6 closes the loop: the page that comes out is checked against the
sample you wrote first.</p>

<h2 id="beyond-reports">Beyond Reports</h2>

<p>The approach works wherever the problem is shaped by data with a clear structure: reports,
file formats, batch jobs, data moved between systems, parsers, API payloads, documents,
and screens. In each of them something comes out with a shape you can draw, and the
program follows that shape.</p>

<p>It helps less when the hard part lies somewhere else:</p>

<ul>
  <li><strong>Events over time.</strong> In a GUI, a workflow, or a device controller, the structure is the
order in which things happen, not a file. The five questions still apply to that order,
but the diagram is no longer the whole design.</li>
  <li><strong>Algorithms.</strong> In search, optimization, or numerical code the output is often a single
number. The work is in the computation, and the shape of the output tells you little.</li>
  <li><strong>Concurrency and distribution.</strong> Message order, partial failure, and consistency are
the hard parts. Structure helps with the messages, not with the timing.</li>
  <li><strong>Exploratory work.</strong> If nobody knows yet what should come out, you cannot design from
it. Build a prototype first, then draw the structure.</li>
</ul>

<h2 id="techniques-to-explore">Techniques to Explore</h2>

<p>Each technique below takes one idea from this post further.</p>

<ul>
  <li><strong>Specification by example and golden tests</strong> (passes 1 and 6). Agree on concrete
samples before writing code, then keep them as tests.</li>
  <li><strong>Algebraic data types</strong> (passes 1 and 2). Product types for sequence and sum types for
<code class="language-plaintext highlighter-rouge">⊕</code> put the diagram into the type system; an exhaustive <code class="language-plaintext highlighter-rouge">match</code> lets the type checker
enforce it.</li>
  <li><strong>Structural recursion</strong> (pass 3). The code follows the shape of the data. A choice
(<code class="language-plaintext highlighter-rouge">⊕</code>) becomes a <code class="language-plaintext highlighter-rouge">match</code> with one case per alternative, and each part gets its own call.
Pass 3 already does this: <code class="language-plaintext highlighter-rouge">build_report</code> calls <code class="language-plaintext highlighter-rouge">build_store</code>, which calls <code class="language-plaintext highlighter-rouge">signed</code>. It
becomes recursion when the data contains itself, such as a folder inside a folder: the
function calls itself on the inner one. The parts get smaller, so it always ends.</li>
  <li><strong>Parse, don’t validate</strong> (pass 4). Turn raw input into types that cannot hold invalid
data. In Python, Pydantic or a small constructor per type does this.</li>
  <li><strong>Railway-oriented programming</strong> (passes 4 and 5). Functions return a value <em>or</em> an
error, and an error skips the rest of the work.</li>
  <li><strong>Generators and stream pipelines</strong> (structure clash). The two programs of a clash
become two generators, joined the way a Unix pipe joins two commands. <code class="language-plaintext highlighter-rouge">itertools</code> has
most of the plumbing.</li>
  <li><strong>Property-based testing</strong> (pass 6). Tools such as Hypothesis generate inputs from a
description of the data; the counts in the diagram, (0,1) and (1,n), become the rules.</li>
  <li><strong>Contract-first APIs.</strong> For a service, the output is the response. Write the OpenAPI
or JSON Schema contract first, then the code behind it.</li>
</ul>

<h2 id="from-theory-to-tool">From Theory to Tool</h2>

<p>This post is the theory, and the companion project is the practice. The third part is a
tool: an <a href="https://github.com/zlatozar/zlatozar.github.io/tree/main/examples/warnier-orr-diagrams/skills/warnier-orr-design">Agent Skill</a> that gives the same steps to a coding agent. Before it
writes code, the agent writes the output sample and both trees, and checks for a
structure clash. It stops twice for your approval: after the sample, and when it finds
a clash. The skill decides only the structure inside one use case. The names come from
your domain, and the architecture and style come from your project. The companion README
shows how to install it.</p>

<hr />

<h2 id="bibliography">Bibliography</h2>

<ul>
  <li>Kirk Hansen, <a href="https://www.amazon.com/Data-Structured-Program-Design-Hansen/dp/0131968416"><em>Data Structured Program Design</em></a> (Ken Orr &amp; Associates,
1983; Prentice Hall, 1986). The source of the classic names used here.</li>
  <li>Michael A. Jackson, <a href="https://www.amazon.com/Principles-Program-Design-APIC-Jackson/dp/0123790506"><em>Principles of Program Design</em></a> (Academic Press,
1975).</li>
  <li>Charles Wetherell, <a href="https://www.amazon.com/Etudes-Programmers-Charles-Wetherell/dp/0132918072"><em>Etudes for Programmers</em></a> (Prentice Hall, 1978).</li>
</ul>]]></content><author><name>Zlatozar Zhelyazkov</name></author><category term="Architecture" /><category term="warnier-orr" /><category term="ddd" /><category term="hexagonal-architecture" /><category term="functional-programming" /><category term="python" /><category term="design" /><summary type="html"><![CDATA[Warnier/Orr design revisited with Kirk Hansen's book: output-first thinking, six passes with modern names, validation at the boundary, and how it fits DDD, Hexagonal Architecture, and functional Python.]]></summary></entry><entry><title type="html">The Essence of Domain-Driven Design</title><link href="https://zlatozar.github.io/the-essence-of-domain-driven-design/" rel="alternate" type="text/html" title="The Essence of Domain-Driven Design" /><published>2024-10-15T16:30:00+00:00</published><updated>2024-10-15T16:30:00+00:00</updated><id>https://zlatozar.github.io/the-essence-of-domain-driven-design</id><content type="html" xml:base="https://zlatozar.github.io/the-essence-of-domain-driven-design/"><![CDATA[<p><em>This is the text of my talk at
<a href="https://dev.bg/event/software-architecture-filosofiya-na-izgrazhdaneto-na-softuerni-sistemi-ili-the-essence-of-domain-driven-design/">DEV.BG Software Architecture</a>
on 15 October 2024. I gave the talk in Bulgarian. Here it is in English.</em></p>

<h2 id="a-short-introduction-images-and-models">A Short Introduction: Images and Models</h2>

<p>Hello, everyone. This is the first time I speak at such a big forum, so please forgive me
if I am a little nervous.</p>

<p>I decided to start from far away. At the beginning, everything will seem too abstract to
you, but in the second half of the talk the pieces will start to fall into place. Before
we look at DDD, I will ask the following philosophical question: <strong>What makes software
good?</strong></p>

<p>Let me open a bracket here. I assume that most of you already know DDD, so this
presentation will stay at a higher level.</p>

<p>My goal is to push you to think in the core ideas of DDD, and to highlight the principles
behind this methodology. In a way, I want to create a mental image of this philosophy of
building software models.</p>

<p>If you think about it, education is exactly this: creating images, mental models, and
ideas. The essence is in the word “image”!</p>

<blockquote class="callout callout--note">
  <p><strong>Lost in translation</strong></p>

  <p>In Bulgarian, the word for education, <em>образование</em> (obrazovanie), comes from <em>образ</em>
(obraz), “image”.</p>
</blockquote>

<p>Unfortunately, in many companies the DDD methodology is not established. Teams work out of
habit, or, if DDD is introduced, it stays too shallow. Nobody explains its essence. So
what I am going to tell you will seem not only abstract, but also unusual.</p>

<p>In general, it is hard to establish good practices, because they need to be promoted
among the teams. This does not happen. Little by little, under the pressure of deadlines,
we do what we know best. Our ego wins, and “our way” is the best way. Is it really? How
many of your ideas have stood the test of time? Because this is the main criterion.</p>

<p>This ends my introduction. To close it, I want to remind you that <strong>knowledge is not
given, it is taken</strong>. No matter how many presentations you attend, you have to show
interest yourselves, start reading, and go deeper.</p>

<p>Today you will not see a concrete implementation. I will present the ideas in principle
and give you the books you need. They contain enough examples.</p>

<h2 id="building-shared-understanding">Building Shared Understanding</h2>

<p>Let’s start philosophizing.</p>

<p>Have you ever asked yourselves what our work is? The work of a programmer?</p>

<p>As programmers, we must take a given real-life situation or process and move it into the
virtual world of the computer. In other words, into executable code. This is not an easy
task at all, because we must not only understand the goal, but also describe the process
or the situation in the language of the computer.</p>

<p>The description requires us to know the meaning of the words, and the meaning is given by
a precise definition.</p>

<p>The team that works on the task must build a shared understanding, a “co-knowledge”. This
means that we all think in the same way about the task in front of us. Each of us has a
mental model of the domain. If one person understands one thing and another person
something else, we get surprising results.</p>

<blockquote class="callout callout--note">
  <p><strong>Lost in translation</strong></p>

  <p>The slide title used the Bulgarian word <em>съ-знание</em> (sa-znanie). Written as one word,
it means “consciousness”. With the hyphen, it reads literally as “co-knowledge”:
knowing together, just like the Latin <em>con-scientia</em>.</p>
</blockquote>

<p>Let’s look at an example:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>All volcanoes are mountains.
All geysers are volcanoes.
--------------------------------------
Therefore, all geysers are mountains.
</code></pre></div></div>

<p>Here the word “volcano” is used in two different senses:</p>

<ul>
  <li>the first is a raised landform;</li>
  <li>the second is an erupting spring.</li>
</ul>

<h3 id="the-first-law-of-logic">The First Law of Logic</h3>

<blockquote class="callout callout--commandment">
  <p><strong>The first law of logic</strong></p>

  <p>In a given reasoning, argument, or discussion, every concept must be used in one and the
same sense.</p>
</blockquote>

<p>Definitions of the concepts alone are not enough. To draw correct conclusions, we must
follow the laws of logic. If we break them, our work will lead us to wrong results.</p>

<p>There are four laws of logic, but I will not go into them in detail. I highlight only the
first one, because it concerns our topic.</p>

<p>The first conclusion is that the program must be logically correct, but it all starts
with the definition of the concepts.</p>

<p>A small digression. There are also many concepts that are hard to define correctly, and
everyone puts a different meaning into them. For example, the word “freedom”.</p>

<p>Unfortunately, politicians and advertisers work with such “watered-down” concepts. Such
concepts must be placed in a specific context.</p>

<h2 id="how-do-we-describe-concepts-to-the-computer">How Do We Describe Concepts to the Computer?</h2>

<blockquote class="callout callout--key">
  <p><strong>Key point</strong></p>

  <p>A computer manipulates symbols that reflect the environment.</p>
</blockquote>

<p>So, let’s assume that we have already agreed on the definitions by discussing them with
the stakeholders.</p>

<p>The computer is blind and deaf, and it has no mind. The only thing we can do is list the
properties of the object.</p>

<p>Properties are symbolic variables that have some value. Together they build a picture for
the “blind” computer. In a way, the computer “touches” them and recognizes what this
concept means.</p>

<p>The analogy is this. As programmers, we look at a class. We read its fields and the
actions performed on them, and this way we understand what the class is for.
Unfortunately, we humans always forget that we are intelligent beings: adding comments
speeds up the work many times.</p>

<p>Anyway… Let’s sum up what we have so far.</p>

<p>We have built a shared understanding in the team through definitions, and we describe
reality through the properties of objects, using symbols.</p>

<p>Is this enough, in your opinion? Of course NOT. We need to remove what is unnecessary. We
need abstraction.</p>

<h2 id="abstraction">Abstraction</h2>

<blockquote class="callout callout--key">
  <p><strong>Key point</strong></p>

  <p>Abstraction is achieved by taking away and adapting.</p>
</blockquote>

<p>It is very hard to build a complete picture, because the description must be as short as
possible, but, on the other hand, complete enough. We cannot have both at the same time.
Therefore, we must concentrate and describe things for the specific case.</p>

<p>Abstraction is achieved by taking away, or in other words, by cutting off. Just as a
sculptor takes away material to reach the right shape.</p>

<p>The rule that we programmers follow is this: first we look at the actions that must be
performed (the future methods in the code). Only then do we look for the properties of the
object (the fields) that can help us implement them.</p>

<p>Short, abstract, and with a lot of talent: this form of writing is called poetry. Let’s
look at a popular verse.</p>

<h3 id="programmers-as-creators">Programmers as Creators</h3>

<figure class="post-figure">
  <a href="/assets/images/the-essence-of-domain-driven-design/poem-as-code.png">
    <img src="/assets/images/the-essence-of-domain-driven-design/poem-as-code.png" width="789" height="311" loading="lazy" alt="A Bulgarian stanza of four lines with hand-written code notes: night =
              true and moonlight = rise above the first line, a red bracket labeled next
              sprint next to lines two and three, and mountain.startTheSong under the
              last line." />
  </a>
  <figcaption>A stanza by Hristo Botev, annotated as code.</figcaption>
</figure>

<blockquote class="epigraph">
  <p>Evening falls, the moon rises,<br />
stars strew the vault of heaven;<br />
the forest murmurs, the wind blows,<br />
the Balkan sings a hajduk song!</p>

  <p>— Hristo Botev, “Hadji Dimitar” (1873)</p>
</blockquote>

<blockquote class="callout callout--note">
  <p><strong>About the poem</strong></p>

  <p>This is the seventh stanza of “Hadji Dimitar” by Hristo Botev, one of the best-known
poems in Bulgarian. The translation above is mine and literal. “The Balkan” is the
Balkan Mountains. A hajduk was a rebel who fought against Ottoman rule. The notes on the
picture turn the first line into <code class="language-plaintext highlighter-rouge">night = true</code> and <code class="language-plaintext highlighter-rouge">moonlight = rise</code>, leave lines two
and three for the “next sprint”, and turn the last line into
<code class="language-plaintext highlighter-rouge">mountain.startTheSong("Капитан Петко войвода")</code>. Captain Petko Voivoda was a famous
hajduk leader.</p>
</blockquote>

<p>How would you turn this into code? It is not easy at all. In this case, it is impossible,
because the poetry gets lost.</p>

<p>You must go deep into every word or expression and find its essence. Then you must
explain every assignment: what does it mean?</p>

<p>This is why comments in the code are so important. How many of you write comments on the
fields of a class?</p>

<p>The Balkan cannot sing, but we still gave it this property. We are not bound to the
physical world. We create our own virtual world.</p>

<h3 id="programmers-as-dreamers">Programmers as Dreamers</h3>

<figure class="post-figure">
  <a href="/assets/images/the-essence-of-domain-driven-design/metromap-as-abstraction.jpeg">
    <img src="/assets/images/the-essence-of-domain-driven-design/metromap-as-abstraction.jpeg" width="834" height="786" loading="lazy" alt="The Sofia Metro map. Four colored lines, red, yellow, blue, and green, are
              drawn as straight segments with stations, transfer points, and a legend." />
  </a>
  <figcaption>The Sofia Metro map (Metropolitan EAD): colors and straight lines that do
    not exist in reality.</figcaption>
</figure>

<p>We may need to add properties to a concept that are not typical for it, but that help us
express ourselves better. We need them, so to speak, to get the job done.</p>

<p>The metro lines in the example are not colored in reality, but the colors make a clear
separation. And of course, the lines are not that straight either.</p>

<p>To make a good abstraction, we must understand well the goal we are aiming for. In this
case, we want to orient the passengers, not to give a technical description of the metro
lines themselves.</p>

<h2 id="kinds-of-complexity">Kinds of Complexity</h2>

<p>The slide named two kinds of complexity:</p>

<ul>
  <li><strong>Essential</strong></li>
  <li><strong>Accidental</strong> (in Bulgarian, I translated it freely as “organizational”)</li>
</ul>

<p>We work in production, on the assembly line that makes software. Every production needs a
good organization of the work processes. What do I mean?</p>

<p>When a specific task comes to you, it has a complexity of its own: the <strong>essential</strong>
complexity. In many cases, you will be prepared to solve it. These are the typical
techniques that we learn at university or in our first years of practice as programmers.</p>

<p>If this were the only complexity, there would not be so many failed projects.</p>

<p>Unfortunately, building any system also brings another complexity, the so-called
<strong>accidental</strong> complexity. Let’s look at it in more detail, because it affects both the
organization of the processes and the architecture.</p>

<p>Imagine that you have to save something in the database. At first glance, it is quite
trivial, but is it really? Besides the save itself, you must:</p>

<ul>
  <li>Check whether you have the context you need to decide what to save.</li>
  <li>Deal with a database that is not organized well enough, so you need to do “hacks”. Are
you prepared enough? Whom do you ask?</li>
  <li>The record is saved. Is it easy to write tests?</li>
  <li>You write the test, but it sometimes passes and sometimes fails in the GitHub pipeline.
Why? How do you diagnose it quickly?</li>
  <li>There are many challenges at the level of the organization, too. You use an outdated
technology. Will you be able to hire new colleagues quickly?</li>
  <li>You have a better idea. How does it reach the people who make decisions?</li>
  <li>After you finish your task, in how many other places must you mark it as done? And so
on.</li>
</ul>

<p>It is important to understand that exactly this complexity blocks the development of the
project and turns it into a <a href="http://www.laputan.org/mud/">Big Ball of Mud</a>, not to mention
what it does to people’s motivation.</p>

<p>The goal of good companies is to reduce this complexity at the level of the organization.
A successful company is one that keeps the added complexity under control.</p>

<h2 id="summary-what-makes-software-good">Summary: What Makes Software Good?</h2>

<p>So far, we have described the following philosophical directions that we must follow when
we write software:</p>

<ul>
  <li>building a shared understanding;</li>
  <li>drawing logically correct conclusions;</li>
  <li>describing properties with symbols;</li>
  <li>building abstraction;</li>
  <li>and the last one, keeping complexity under control.</li>
</ul>

<p>In the books, you will read that a correct description is the first thing that the DDD
methodology deals with. Yes, that is true, but it is not the only thing.</p>

<p>DDD also helps us build the right abstraction, but this abstraction will be much better if
we go deep into the properties of the objects. The DDD methodology does not teach us this;
it only stresses its importance. It does not tell us how to control complexity at all
levels, only at the level of the code.</p>

<p>In other words, this methodology does not cover everything, but it is a very important
part of the process of building software.</p>

<blockquote class="callout callout--key">
  <p><strong>From an architectural point of view</strong></p>

  <p>Using DDD guarantees that we create a single picture of the problem, with clear
boundaries in the code. To reach perfection, however, we also need the skill to think
logically, to create the right abstractions, and to keep complexity under control.</p>
</blockquote>

<h2 id="describing-concepts-correctly">Describing Concepts Correctly</h2>

<blockquote class="callout callout--key">
  <p><strong>Key point</strong></p>

  <p>Create the ubiquitous language.</p>
</blockquote>

<p>I suggest that we start looking at the methodology itself, and try to stress the essence
of its rules.</p>

<p>So… it will not surprise us that DDD suggests starting with the definition and
description of the concepts. These are the nouns in the problem statement.</p>

<p>Together, they are called domain objects, and, as you know, DDD splits them into two
types: Value Objects and Entity Objects.</p>

<h3 id="value-objects">Value Objects</h3>

<p>The slide compared the theory with a practical example, <code class="language-plaintext highlighter-rouge">Money</code>:</p>

<table>
  <thead>
    <tr>
      <th>Value object (theory)</th>
      <th><code class="language-plaintext highlighter-rouge">Money</code> (practice)</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Has attributes (entities or value objects), and they define its equality</td>
      <td>Has <code class="language-plaintext highlighter-rouge">Value</code> and <code class="language-plaintext highlighter-rouge">Currency</code></td>
    </tr>
    <tr>
      <td>Cannot have state-changing methods</td>
      <td>Its <code class="language-plaintext highlighter-rouge">Add</code> method returns a new <code class="language-plaintext highlighter-rouge">Money</code> instance</td>
    </tr>
  </tbody>
</table>

<p>These objects are relatively easy to find, because they can be combined or they take part
in arithmetic operations. When we meet the business and they tell us about some kind of
arithmetic, we are almost certainly talking about Value Objects. Most often, they express
a measure, a quantity, a count, and so on.</p>

<p>DDD describes very strictly the rules that we must follow when we build this kind of
object. Value Objects:</p>

<ul>
  <li>are immutable;</li>
  <li>have no identifier (ID);</li>
  <li>can validate themselves;</li>
  <li>define <code class="language-plaintext highlighter-rouge">equals</code> and <code class="language-plaintext highlighter-rouge">hashCode</code> based on their attributes;</li>
  <li>have <code class="language-plaintext highlighter-rouge">toString</code> for easy checks in the log;</li>
  <li>can exist in any number in the program;</li>
  <li>define methods that form their algebra;</li>
  <li>have no side effects;</li>
  <li>do not keep state.</li>
</ul>

<p>The Factory Method pattern is very often used to create them. If they are very large, the
Flyweight pattern is used.</p>

<p>A small architectural digression: it is good to make our application stateless. If it is
stateless, it keeps state only in the database or in the client.</p>

<h3 id="entity-objects">Entity Objects</h3>

<p>The slide compared the theory with a practical example, <code class="language-plaintext highlighter-rouge">Product</code>:</p>

<figure class="post-figure">
  <a href="/assets/images/the-essence-of-domain-driven-design/entity-object.png">
    <img src="/assets/images/the-essence-of-domain-driven-design/entity-object.png" width="1182" height="670" loading="lazy" alt="Two diagrams split by a dashed line. Theory: an Entity has an identity that
              defines its equality, has attributes (entities or value objects), and can
              have state-changing methods. Practice: a Product has an ID, Options, a
              Retail price, and a Selling price, and its Change_Price_To method changes
              the Selling price." />
  </a>
  <figcaption>An Entity in theory and in practice: the <code>Product</code>.</figcaption>
</figure>

<p>Entity Objects have a long life cycle! Let’s look at this characteristic in more detail.</p>

<p>What do we mean by “life cycle”? Usually, these objects change “drop by drop” until they
reach the desired state, and after a change they are most often saved in the database.
These states must be known in advance, and we must try to keep the system from falling
into uncertainty.</p>

<p>By “uncertainty” I mean that an object must not go into a state that is unknown to us. To
avoid this, for every Value Object we must define its invariants.</p>

<p>What are invariants?</p>

<dl class="definition">
  <dt>invariant <em>noun</em></dt>
  <dd>The truths about an object.</dd>
</dl>

<p>You must ask yourself: what makes the object true? An example: we have the object Hotel.
What makes a hotel a hotel? The rooms. If there are no rooms, it is not a hotel.</p>

<p>Or the box of medical instruments. It holds a certain number of instruments. If this
number is exceeded, the box cannot be closed and the process cannot continue. It turns
into a “non-box”.</p>

<p>After every change of these objects, we must make sure that the object is in a valid
state. This is why we have logic in the code that checks it.</p>

<p>When we have the invariants, the logic in the code becomes much simpler. We are sure that
we work in a controlled environment, and we do not need extra checks.</p>

<p>Here are the rules for writing Entity Objects:</p>

<ol>
  <li>They are named (natural IDs are preferred).</li>
  <li>Two objects are equal if they have equal IDs.</li>
  <li>They have a long life cycle.</li>
  <li>They are saved in the database.</li>
  <li>They have rules that forbid certain states (invariants).</li>
  <li>We decide carefully what can change and what cannot.</li>
</ol>

<p>A digression. It is very useful that Entity Objects are named, because in some cases it is
convenient to keep a reference to the Entity Object instead of the object itself. We keep
only its ID.</p>

<p>The 6th rule, so to speak, defines the first level of abstraction. An Entity Object works
with some set of properties, but it defines exactly what operations can be performed on
them!</p>

<h2 id="how-do-we-validate-incoming-data">How Do We Validate Incoming Data?</h2>

<p>We have the domain objects, but the data that changes their state comes from outside.</p>

<p>To make correct transitions between states, we need correct input data. You may have
heard the maxim: garbage in, garbage out.</p>

<p>The checks happen in a strictly defined order:</p>

<ol>
  <li><strong>Origin</strong>: Is the data from a legitimate sender?</li>
  <li><strong>Size</strong>: Is it reasonably big?</li>
  <li><strong>Lexical content</strong>: Does it contain the right tokens and encoding? In other words, do
we understand every word of the sentence?</li>
  <li><strong>Syntax</strong>: Is it in the right format? This is a grammar check: is the sentence
grammatically correct?</li>
  <li><strong>Semantics</strong>: Does the data make sense in the given context? Is it useful to us?</li>
</ol>

<p>Valid data protects our system from certain kinds of attacks. Our product becomes “secure
by design”.</p>

<h3 id="parse-dont-validate">Parse, Don’t Validate</h3>

<blockquote class="callout callout--commandment">
  <p><strong>Slogan</strong></p>

  <p>Parse, do not validate!</p>
</blockquote>

<p>You may have met this slogan. Let’s see how it fits the rules above.</p>

<p>An example: a JSON document arrives at the input. Turn it into a class. If you cannot, the
data is invalid.</p>

<p>In other words, let the compiler validate the structure of the data. This is why we aim to
type everything and not to work with primitive types. Every parameter, field, or object
must be a domain object.</p>

<p>It is a very bad practice to do validation (checking field by field), because to have good
validation, you practically have to write a parser, and that is hard. <strong>Parsers are a
science.</strong></p>

<p>The good news is that we rarely have to write the parser ourselves. Most frameworks
already map the incoming request to a class, and this mapping is our structural
validation. We can also validate the request against a schema, for example a JSON Schema
or an OpenAPI specification, before it reaches the domain logic.</p>

<h3 id="be-liberal-in-what-you-accept">Be Liberal in What You Accept</h3>

<blockquote class="callout callout--commandment">
  <p><strong>Rule</strong></p>

  <p>Be liberal with what you accept, and conservative in what you emit.</p>

  <p>What is valuable for me (in this life)?</p>
</blockquote>

<p>This is another common rule. In short, read it this way: validate only what concerns you.
Do not put unnecessary things in the result, only as much as the process needs to
continue.</p>

<p>Be careful with what you give. Once a field is in the contract, somebody will start to
depend on it. Taking it back later is a backward-incompatible change. It is always easier
to add a field than to remove one.</p>

<h2 id="what-should-the-database-contain">What Should the Database Contain?</h2>

<p>From the point of view of DDD, this is a philosophical look at the eternal question.</p>

<p>It is very important to clarify this, because it is key when we describe the different
scenarios. The goal is to shape the right relationship between the domain logic and the
database.</p>

<p>What we keep in the database is actually the foundation on which we build the whole
software product.</p>

<p>DDD is about a strict separation between the domain objects and the database. The
database keeps the relations, and the domain logic interprets them.</p>

<p>Can you give a definition of a relation? We said that before we start working, we must
agree on the definition. The word “relation” is used often, but a precise definition is
hard.</p>

<dl class="definition">
  <dt>relation <em>noun</em></dt>
  <dd>A labeled connection between concepts.</dd>
</dl>

<p>Let’s give some examples:</p>

<ul>
  <li>Ivan <em>likes</em> jazz.</li>
  <li>Georgi <em>has</em> a guitar.</li>
  <li>Radka <em>loves</em> to cook.</li>
</ul>

<p>“Likes”, “has”, and “loves” are the labeled connections. That is clear.</p>

<p>The word “concept” also needs an explanation. Dictionaries of synonyms and explanatory
dictionaries do a great job here. A concept is a notion, an understanding, an opinion.</p>

<p>Here is the rule:</p>

<blockquote class="callout callout--key">
  <p><strong>Key point</strong></p>

  <p>The database keeps our understanding of reality. It describes the real world, or a given
area of life, work, or relationships.</p>
</blockquote>

<p>This is why it is important to agree on which relations exist as a given. These are the
axioms on which we can stand and build the system.</p>

<p>I warned you that my presentation would be unusual :)</p>

<p>An example from our company:</p>

<ul>
  <li>A box contains one or more medical instruments.</li>
  <li>Instruments are either ours or third-party.</li>
  <li>A repair is approved by the director of the hospital department.</li>
</ul>

<p>These understandings of ours must be reflected as connections (relations) in the database.</p>

<h3 id="mapping-is-not-always-11">Mapping Is Not Always 1:1</h3>

<figure class="post-figure">
  <a href="/assets/images/the-essence-of-domain-driven-design/mapping-not-one-to-one.png">
    <img src="/assets/images/the-essence-of-domain-driven-design/mapping-not-one-to-one.png" width="809" height="708" loading="lazy" alt="A hand-drawn sketch. A diamond labeled Domain Objects sits above a box
              labeled DataBase relations. Red shapes labeled Mapping connect each domain
              object to only some of the related records in the database." />
  </a>
  <figcaption>Each domain object maps only a part of the relations in the
    database.</figcaption>
</figure>

<p>The domain logic (the program), in turn, is an interpretation of the objective truth.</p>

<p>What does this mean?</p>

<p>It means that domain objects can take “a part of the reality” that is in the database. For
example, the worker who repairs the medical instrument does not need to know how much
money was paid for the instrument.</p>

<p>In other words, we must go deep into the specific domain and decide which part of the
relations (understandings) must be visible. Then we define their behavior. As you can
guess, these domain objects are Entity Objects.</p>

<p>And one more very important thing. DDD insists that we define the meaning of the concepts
according to the specific domain. This means that the domain logic interprets reality
according to the specific case.</p>

<p>An example: in one domain, the worker can be seen as a craftsman with a certain
qualification. In accounting, the same worker is a first name and a last name with a
certain salary.</p>

<h2 id="the-abstract-view-of-ddd">The Abstract View of DDD</h2>

<figure class="post-figure">
  <a href="/assets/images/the-essence-of-domain-driven-design/ddd-abstract-view.png">
    <img src="/assets/images/the-essence-of-domain-driven-design/ddd-abstract-view.png" width="934" height="620" loading="lazy" alt="A hand-drawn diagram of nested boxes. A Data source arrow enters the outer
              box at Data Validation and transformation. It flows into Bounded Context
              creation with Factories, which contains Aggregates with Domain Objects
              inside, and Domain Services." />
  </a>
  <figcaption>The abstract view of DDD: validation first, then factories create the
    bounded context with its aggregates and domain services.</figcaption>
</figure>

<p>Here is what the picture looks like so far. It is too abstract, but it will help us
organize the structure of the project.</p>

<p>What is left to “cover” in this picture?</p>

<h2 id="domain-services">Domain Services</h2>

<blockquote class="callout callout--key">
  <p><strong>Domain services</strong></p>

  <p>Domain services encapsulate domain logic and concepts that are not naturally modeled as
value objects or entities in your model, and are NOT typical CRUD operations.</p>

  <ul>
    <li>They are stateless.</li>
    <li>They are highly cohesive, meaning they are specialized in doing one thing and one
thing only.</li>
  </ul>
</blockquote>

<p>Let’s start with Domain Services.</p>

<p>Very often, a domain service is a function or a set of functions. In a way, it is simply
an “external service” that the domain logic has to use. Immediately, a familiar picture
appears in your heads: the Util methods, right?</p>

<p>These Util methods are not bad by themselves, but they are a sign that no methodology or
strategy was used to build the product. DDD has such a methodology, and there we follow a
convention: <code class="language-plaintext highlighter-rouge">Class.staticMethod()</code>.</p>

<p>We try to keep them stateless.</p>

<h2 id="aggregates">Aggregates</h2>

<blockquote class="callout callout--key">
  <p><strong>What are aggregates?</strong></p>

  <p>Aggregates are a kind of framework that exposes methods for invoking a command, or
commands, to make a particular action happen. Actions manipulate domain objects.</p>

  <p>An aggregate has a concrete state, and it depends on the current state of the aggregate
how, and if, certain operations can be performed.</p>
</blockquote>

<p>What do we have so far?</p>

<p>Small objects, Entity or Value Objects, and service (external) functions. In practice,
these are our building blocks. You can imagine them as Lego pieces. They have a good
specification, they are distinguishable, and we can compare them. Most important, we can
reuse them to build something bigger.</p>

<p>In software, when we describe an action, it very often changes several of these small
objects. It was the same with Entity Objects: there, the fields of the object changed.</p>

<p>Here is an invented action from our process: “I send a medical instrument for repair.”</p>

<ol>
  <li>We mark the instrument as unusable.</li>
  <li>We classify the instrument.</li>
  <li>We put the instrument in the box for broken instruments.</li>
  <li>Or we request a new one.</li>
</ol>

<p>DDD recommends making generalizations. I will perform these actions, but under the hat of
a single method call. I create a new level of abstraction. <strong>The Aggregate Root is a
gateway.</strong></p>

<p>Why?</p>

<p>Because behind these actions there are many other details that we miss “at first
reading”. The instrument is an Entity; so far, so good. But what about “putting it in the
box”? How many instruments at most can go in the box? Are they sorted by type? Do we need
permission?</p>

<p>Of course, we can do it line by line, but this will create problems when we maintain the
code. In a way, we do unnecessary micromanagement at the level of the code.</p>

<p>Aggregates gather several steps into one action. Some sources also call this a “unit of
work”.</p>

<p>We ask for the operation to be done without caring about the details. You just call the
aggregate method: <code class="language-plaintext highlighter-rouge">sendForRepair(instrumentId)</code>.</p>

<p>In essence, aggregates are Entity Objects with a higher, 2nd level of abstraction. They no
longer change fields; they change the states of Entity Objects.</p>

<p>There is a rule in our profession. Follow it!</p>

<blockquote class="callout callout--commandment">
  <p><strong>A rule of our profession</strong></p>

  <p>Every problem becomes solvable if you add one more level of abstraction.</p>
</blockquote>

<h3 id="views-only-hide-things">Views Only Hide Things</h3>

<blockquote class="callout callout--commandment">
  <p><strong>Proven by life</strong></p>

  <p>Views only hide things, never remove them.</p>
</blockquote>

<p>Let’s not forget that reality is in the database. Through the aggregates, we may show
only a part of it, but this does not mean that the rest does not exist.</p>

<p>Usually, what we see as users is only the tip of the iceberg.</p>

<h3 id="rules-for-writing-aggregates">Rules for Writing Aggregates</h3>

<ol>
  <li>The aggregate must be the entry point for every operation with a higher level of
abstraction.</li>
  <li>It must not manipulate more than three Entity Objects.</li>
  <li>It must have a global (universal) ID.</li>
  <li>It must make sure that all objects are in a valid state.</li>
  <li>It must enforce the invariants set by the business after every transaction.</li>
  <li>Aggregates are saved in the database.</li>
</ol>

<p>These are the rules. I want to draw your attention to two things.</p>

<p>First, the invariants. You probably remember that every Entity object also has
invariants. DDD recommends following “the rules of the game” at all levels. This approach
guarantees the correctness of the program.</p>

<p>Second, saving the aggregate in the database. What is important here?</p>

<p>Imagine the aggregate as one complex, you could even say composite, Entity Object. This
means that it spans more than one table, if we use a relational database.</p>

<p>The benefits are:</p>

<ul>
  <li>We keep a consistent state in the database (save within a transaction).</li>
  <li>We work with a higher abstraction, which should always be our goal.</li>
  <li>Hibernate is made to work this way. It brings the whole scene of action to the surface.</li>
</ul>

<p>But we must also ask ourselves the following questions:</p>

<ul>
  <li>Can we easily do the mapping between the database and the aggregate?</li>
  <li>If we have to change the database “by hand”, how easy will the change be?</li>
  <li>What type of database should we choose?</li>
</ul>

<p>The main problem with this approach is inheritance, if it exists in the code.</p>

<h3 id="moving-between-states">Moving Between States</h3>

<p>The slide showed the states of an order as a state diagram:</p>

<figure class="post-figure">
  <a href="/assets/images/the-essence-of-domain-driven-design/aggregate-states.png">
    <img src="/assets/images/the-essence-of-domain-driven-design/aggregate-states.png" width="948" height="744" loading="lazy" alt="A state diagram of an order. Start leads to Under configuration, then to
              Complete but not paid. From there the order is either Paid or Complete but
              payment rejected, which goes back to Under configuration. Paid leads to
              Shipped. Shipped leads to Delivered or Misplaced; Misplaced leads back to
              Shipped or to Lost. Delivered leads to Rejected, Under return, Returned,
              and Repaid. Lost, Delivered, and Repaid are marked as end states." />
  </a>
  <figcaption>The states of an order. Lost, Delivered, and Repaid are end
    states.</figcaption>
</figure>

<p>I definitely want to mention one good technique for building complex aggregates.</p>

<p>Aggregates, just like entity objects, change their state over time. They have a life
cycle.</p>

<p>It may turn out that the aggregate has many states that it must go through. In such
cases, it is best to implement the description as a finite-state automaton (FSA, plural:
automata).</p>

<p>This way, we describe clearly which events (messages) lead to a change. Also, the code
becomes much more readable.</p>

<h3 id="make-illegal-states-unrepresentable">Make Illegal States Unrepresentable</h3>

<blockquote class="callout callout--commandment">
  <p><strong>The goal of all constraints</strong></p>

  <p>Make illegal states unrepresentable!</p>
</blockquote>

<p>It is important that our system never goes into an undefined state. As we said, this must
be our maxim when we construct the objects and validate the data.</p>

<p>This way, our domain logic will be free of exceptions, and that makes the code much
cleaner.</p>

<h2 id="creating-the-bounded-context">Creating the Bounded Context</h2>

<blockquote class="callout callout--key">
  <p><strong>Key point</strong></p>

  <p>Aggregates should be instantiated.</p>
</blockquote>

<p>This is the last popular DDD term that I want to talk about.</p>

<p>A bounded context consists of several aggregates. It provides their working environment.
It is the stage on which the action takes place. Roughly speaking, it is a separate
microservice.</p>

<p>How to define it is another philosophical question, outside the scope of this talk. The
most popular methodology for defining it is called
<a href="/event-storming/">EventStorming</a>.</p>

<p>So, for something to work in our system, it must first be instantiated (created).</p>

<p>We must choose the moment of instantiation very carefully, and it must be flexible enough.
For this purpose, creational patterns are used most often.</p>

<p>Here is what we must observe:</p>

<ul>
  <li>It happens at the right moment: in advance (cache) or just before use. Lazy loading or
immediate loading.</li>
  <li>The correctness of the created object is guaranteed: the Builder pattern.</li>
  <li>It is fast enough and saves memory: the Flyweight pattern.</li>
  <li>It is flexible, in other words, it covers many cases: the Template Method pattern.</li>
</ul>

<p>In general, it is not hard to implement a bounded context. The hard part is defining its
boundaries. How big should it be, and what should it contain?</p>

<p>Let’s move to the final part, because this was the last topic I wanted to touch.</p>

<h2 id="in-one-picture">In One Picture</h2>

<p>Here are all the building blocks of DDD in one picture:</p>

<figure class="post-figure">
  <a href="/assets/images/the-essence-of-domain-driven-design/whole-picture.png">
    <img src="/assets/images/the-essence-of-domain-driven-design/whole-picture.png" width="1220" height="766" loading="lazy" alt="The building blocks of DDD. A Client calls Application Services and a
              Factory. Application Services orchestrate only and contain no business
              logic. The Factory creates complex entities, value objects, and aggregates.
              Application Services update the model through the aggregate root and use a
              Repository to persist and hydrate aggregates. The Domain Model holds
              Aggregates A, B, and C, Entities, Value objects, and Domain Services. All of
              this sits inside the Bounded Context." />
  </a>
  <figcaption>The building blocks of DDD inside one bounded context.</figcaption>
</figure>

<p>Let’s follow a request through the picture. The client calls an application service. The
application service only orchestrates; it contains no business logic. When something new
must be created, a factory creates it. When something must change, the change goes through
the aggregate root. The repository saves the aggregates and loads them back.</p>

<p>The business policies and logic live in the domain model: aggregates built from entities
and value objects, plus the domain services. And all of this lives inside one bounded
context.</p>

<p>The conclusions:</p>

<ul>
  <li>Don’t be verbose. Don’t do micromanagement at the level of the code. If your code is too
verbose, the abstraction is not correct. In the same way, if your code needs many
comments, it does not explain itself.</li>
  <li>“Fire and forget” must be our motto. Build an abstraction, and an implementation behind
it, that is so reliable that you simply fire the call. How the process goes in detail
should not matter to you.</li>
  <li>DDD gives us recommendations on how to build our system at several levels of
abstraction: entity, aggregate, and bounded context.</li>
</ul>

<blockquote class="callout callout--key">
  <p><strong>Key point</strong></p>

  <p>The level of professionalism in our profession is measured by the ability to build
abstractions at different levels.</p>
</blockquote>

<p>With these levels, adding new features and testing become much easier. Try to put every
addition to the product at the right level of abstraction.</p>

<p>The aggregate is not the last level of abstraction; you can continue. For example, you can
combine two or more microservices into a new aggregate of a higher level.</p>

<p>DDD does not cover the system requirements directly.</p>

<p>And now, the books.</p>

<h2 id="books">Books</h2>

<p><strong>Recommend a book:</strong></p>

<ul>
  <li>Scott Millett and Nick Tune,
<a href="https://www.wiley.com/en-us/Patterns%2C+Principles%2C+and+Practices+of+Domain+Driven+Design-p-9781118714706"><em>Patterns, Principles, and Practices of Domain-Driven Design</em></a>
(Wrox, 2015). DDD, with C# examples.</li>
  <li>Alan Shalloway and James R. Trott,
<a href="https://www.informit.com/store/design-patterns-explained-a-new-perspective-on-object-9780321247148"><em>Design Patterns Explained: A New Perspective on Object-Oriented Design</em></a>,
2nd edition (Addison-Wesley, 2004). The philosophy of patterns, with Java examples.</li>
</ul>

<p><strong>Recommend a practical book, please:</strong></p>

<ul>
  <li>Dan Bergh Johnsson, Daniel Deogun, and Daniel Sawano,
<a href="https://www.manning.com/books/secure-by-design"><em>Secure by Design</em></a> (Manning, 2019).
DDD as security, with Java examples.</li>
  <li>Tom Hombergs,
<a href="https://www.packtpub.com/en-us/product/get-your-hands-dirty-on-clean-architecture-9781805128373"><em>Get Your Hands Dirty on Clean Architecture</em></a>,
2nd edition (Packt, 2023). A DDD implementation, with Java examples.</li>
</ul>]]></content><author><name>Zlatozar Zhelyazkov</name></author><category term="Architecture" /><category term="ddd" /><category term="domain-modeling" /><category term="value-objects" /><category term="entities" /><category term="aggregates" /><category term="bounded-context" /><category term="talks" /><summary type="html"><![CDATA[The text of my DEV.BG talk about the philosophy behind Domain-Driven Design: shared understanding, definitions, abstraction, complexity, value objects, entities, aggregates, and bounded contexts.]]></summary></entry><entry><title type="html">An FMI Exam Task in Scheme, Part 2</title><link href="https://zlatozar.github.io/fmi-task-part-2/" rel="alternate" type="text/html" title="An FMI Exam Task in Scheme, Part 2" /><published>2012-10-15T16:30:00+00:00</published><updated>2012-10-15T16:30:00+00:00</updated><id>https://zlatozar.github.io/fmi-task-part-2</id><content type="html" xml:base="https://zlatozar.github.io/fmi-task-part-2/"><![CDATA[<p>In <a href="/fmi-task-part-1/">Part 1</a> I described how I reasoned while
solving a task from an FMI exam. It all went in a rather chaotic way, so the final result
gives correct answers, but it does not satisfy me. By the way, the person who showed me
the task passed the exam, although he had to explain at length why he had not solved
this one :)</p>

<p>Here is the code from Part 1 again. So where is the mistake?</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">;; nothing to change</span>
<span class="p">(</span><span class="k">define</span> <span class="nv">count-trace</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">a</span> <span class="nv">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="k">cond</span>
      <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="mi">0</span><span class="p">)</span>
      <span class="p">((</span><span class="nb">eq?</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">))</span> <span class="p">(</span><span class="nb">+</span> <span class="mi">1</span> <span class="p">(</span><span class="nf">count-trace</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">))))</span>
      <span class="p">(</span><span class="k">else</span>
       <span class="p">(</span><span class="nf">count-trace</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">))))))</span>

<span class="p">(</span><span class="k">define</span> <span class="nv">reduce</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">a</span> <span class="nv">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="k">cond</span>
      <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="o">'</span><span class="p">())</span>
      <span class="p">((</span><span class="nb">eq?</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">a</span><span class="p">)</span> <span class="p">(</span><span class="nf">reduce</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)))</span>
      <span class="p">(</span><span class="k">else</span>
       <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nf">reduce</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)))))))</span>

<span class="p">(</span><span class="k">define</span> <span class="nv">revert</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lst</span><span class="p">)</span>
    <span class="p">(</span><span class="k">define</span> <span class="nv">revert-in</span>
      <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lat</span> <span class="nv">rev</span><span class="p">)</span>
        <span class="p">(</span><span class="k">cond</span>
          <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">rev</span><span class="p">)</span>
          <span class="p">(</span><span class="k">else</span>
           <span class="p">(</span><span class="nf">revert-in</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">rev</span><span class="p">))))))</span>
    <span class="p">(</span><span class="nf">revert-in</span> <span class="nv">lst</span> <span class="o">'</span><span class="p">())))</span>

<span class="p">(</span><span class="k">define</span> <span class="nv">freq-*</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lst</span> <span class="nv">func</span><span class="p">)</span>
    <span class="p">(</span><span class="k">let</span> <span class="nv">freq-in</span> <span class="p">((</span><span class="nf">lat</span> <span class="nv">lst</span><span class="p">)</span> <span class="p">(</span><span class="nf">seen</span> <span class="o">'</span><span class="p">()))</span>
      <span class="p">(</span><span class="k">cond</span>
        <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nf">revert</span> <span class="nv">seen</span><span class="p">))</span>
        <span class="p">(</span><span class="k">else</span>
         <span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nf">curr</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)))</span>
           <span class="p">(</span><span class="nf">freq-in</span> <span class="p">(</span><span class="nf">reduce</span> <span class="nv">curr</span> <span class="nv">lat</span><span class="p">)</span>
                    <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">list</span> <span class="p">(</span><span class="nf">func</span> <span class="nv">curr</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">curr</span><span class="p">)</span> <span class="nv">seen</span><span class="p">))))))))</span>

<span class="p">(</span><span class="k">define</span> <span class="nv">count-freq</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="nf">freq-*</span> <span class="nv">lat</span> <span class="nv">count-trace</span><span class="p">)))</span>

<span class="c1">;; (count-freq '(a a b c)) ;; '((2 a) (1 b) (1 c))</span>
</code></pre></div></div>

<h2 id="names-matter">Names Matter</h2>

<p>In Lisp, if you do not know the special forms and the standard functions well, it is very
easy to redefine some of them by accident. People who write Lisp usually know several
dialects, such as Scheme, Common Lisp, or Clojure, and they carry their knowledge from one
to another. That is why nobody would use the name <code class="language-plaintext highlighter-rouge">reduce</code> for a function that removes an
element from a list. For reference, this is what
<a href="https://www.lispworks.com/documentation/HyperSpec/Body/f_reduce.htm"><code class="language-plaintext highlighter-rouge">reduce</code></a> does in
Common Lisp:</p>

<div class="language-lisp highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">reduce</span> <span class="nf">#'</span><span class="nb">*</span> <span class="o">'</span><span class="p">(</span><span class="mi">1</span> <span class="mi">2</span> <span class="mi">3</span> <span class="mi">4</span> <span class="mi">5</span><span class="p">))</span> <span class="c1">; =&gt; 120</span>
</code></pre></div></div>

<p>It reduces the list to one value by applying the given function. So the right name is
<a href="https://www.lispworks.com/documentation/HyperSpec/Body/f_rm_rm.htm"><code class="language-plaintext highlighter-rouge">remove</code></a>, and I keep
the same order of parameters:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nf">remove</span> <span class="nv">elm</span> <span class="nv">ls</span><span class="p">)</span>
  <span class="p">(</span><span class="k">cond</span>
    <span class="p">((</span><span class="nb">null?</span> <span class="nv">ls</span><span class="p">)</span> <span class="o">'</span><span class="p">())</span>
    <span class="p">((</span><span class="nb">equal?</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">ls</span><span class="p">)</span> <span class="nv">elm</span><span class="p">)</span> <span class="p">(</span><span class="nf">remove</span> <span class="nv">elm</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">ls</span><span class="p">)))</span>
    <span class="p">(</span><span class="k">else</span>
     <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">ls</span><span class="p">)</span> <span class="p">(</span><span class="nf">remove</span> <span class="nv">elm</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">ls</span><span class="p">))))))</span>

<span class="c1">;; (remove 'a '(a b c a)) ;; '(b c)</span>
</code></pre></div></div>

<blockquote class="callout callout--note">
  <p><strong>Note</strong></p>

  <p>Racket already has a
<a href="https://docs.racket-lang.org/reference/pairs.html#%28def._%28%28lib._racket%2Fprivate%2Flist..rkt%29._remove%29%29"><code class="language-plaintext highlighter-rouge">remove</code></a>,
and our definition hides it. Be careful: Racket’s <code class="language-plaintext highlighter-rouge">remove</code> deletes only the first
match, so <code class="language-plaintext highlighter-rouge">(remove 'a '(a b a))</code> gives <code class="language-plaintext highlighter-rouge">'(b a)</code>. To delete all matches, Racket has
<code class="language-plaintext highlighter-rouge">remove*</code>, which takes a list of values: <code class="language-plaintext highlighter-rouge">(remove* '(a) '(a b a))</code> gives <code class="language-plaintext highlighter-rouge">'(b)</code>. Our
<code class="language-plaintext highlighter-rouge">remove</code> deletes all matches, as in Common Lisp.</p>
</blockquote>

<h2 id="reversing-a-list">Reversing a List</h2>

<p>So far, this is a small problem. But why did I write <code class="language-plaintext highlighter-rouge">revert</code>? Isn’t <code class="language-plaintext highlighter-rouge">reverse</code> a better
name?</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nb">reverse</span> <span class="nv">seq</span><span class="p">)</span>
  <span class="p">(</span><span class="k">if</span> <span class="p">(</span><span class="nb">null?</span> <span class="nv">seq</span><span class="p">)</span>
      <span class="o">'</span><span class="p">()</span>
      <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">reverse</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">seq</span><span class="p">))</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">seq</span><span class="p">))))</span>

<span class="c1">;; (reverse '(1 2 3 4)) ;; '((((() . 4) . 3) . 2) . 1)</span>
</code></pre></div></div>

<p><code class="language-plaintext highlighter-rouge">reverse</code> is definitely a better name. Also, influenced by <em>The Little Schemer</em>, I used
<code class="language-plaintext highlighter-rouge">cond</code> everywhere. That is not needed: for two branches, <code class="language-plaintext highlighter-rouge">if</code> is enough. Otherwise, my
reasoning was right. To reverse <code class="language-plaintext highlighter-rouge">(1 2 3 4)</code>:</p>

<blockquote>
  <p>Put <code class="language-plaintext highlighter-rouge">(2 3 4)</code>, reversed, in front of <code class="language-plaintext highlighter-rouge">1</code>. Put <code class="language-plaintext highlighter-rouge">(3 4)</code>, reversed, in front of <code class="language-plaintext highlighter-rouge">(2 1)</code>.
Put <code class="language-plaintext highlighter-rouge">4</code> in front of <code class="language-plaintext highlighter-rouge">(3 2 1)</code>.</p>
</blockquote>

<p>In Part 1 I also noticed this:</p>

<blockquote>
  <p>I always pass the <code class="language-plaintext highlighter-rouge">cdr</code> as the first argument, and let the second one build the result
with <code class="language-plaintext highlighter-rouge">cons</code>.</p>
</blockquote>

<p>My mistake is that I did not apply the first idea correctly. <em>Put … in front of …</em>,
again and again: this means recursion, and <strong>at the end</strong> I join the parts with <code class="language-plaintext highlighter-rouge">cons</code>.
So this:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">reverse</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">seq</span><span class="p">))</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">seq</span><span class="p">))</span>
</code></pre></div></div>

<p>follows my reasoning much better than this:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nf">revert-in</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">rev</span><span class="p">))</span>
</code></pre></div></div>

<p>Yes, but I was not careful! Don’t ask me why I put the recursive call first in <code class="language-plaintext highlighter-rouge">cons</code>: it
breaks the golden rule of <code class="language-plaintext highlighter-rouge">cons</code> from Part 1, because the second argument is an atom, not
a list. Still, the result <code class="language-plaintext highlighter-rouge">((((() . 4) . 3) . 2) . 1)</code> is not that discouraging. I only
join the parts in the wrong way:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nb">reverse</span> <span class="nv">items</span><span class="p">)</span>
  <span class="p">(</span><span class="k">if</span> <span class="p">(</span><span class="nb">null?</span> <span class="nv">items</span><span class="p">)</span>
      <span class="o">'</span><span class="p">()</span>
      <span class="p">(</span><span class="nb">append</span> <span class="p">(</span><span class="nb">reverse</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">items</span><span class="p">))</span>
              <span class="p">(</span><span class="nb">list</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">items</span><span class="p">)))))</span>

<span class="c1">;; (reverse '(1 2 3 4)) ;; '(4 3 2 1)</span>
</code></pre></div></div>

<p>The trick here is <code class="language-plaintext highlighter-rouge">(list (car items))</code>. <code class="language-plaintext highlighter-rouge">append</code> takes two lists, so we write <code class="language-plaintext highlighter-rouge">4</code> as
<code class="language-plaintext highlighter-rouge">(4)</code>, and <code class="language-plaintext highlighter-rouge">append</code> collects the pieces into one list. This trick is used very often.</p>

<blockquote class="callout callout--note">
  <p><strong>What it costs</strong></p>

  <p>This version follows the reasoning, but it is slow. <code class="language-plaintext highlighter-rouge">append</code> copies its whole first
argument, so reversing a list of n elements takes O(n²) steps. The accumulator version
<code class="language-plaintext highlighter-rouge">revert-in</code> from Part 1 takes O(n) steps and is tail-recursive. This is how <code class="language-plaintext highlighter-rouge">reverse</code> is
usually written, and Scheme already has it built in; we write our own only to see how it
works. But as you will see below, the final solution does not need to reverse anything.</p>
</blockquote>

<h2 id="a-natural-recursion">A Natural Recursion</h2>

<p>Something similar happened with <code class="language-plaintext highlighter-rouge">freq-*</code>. Again the solution was in front of me, but I
missed it. This is the algorithm I proposed:</p>

<blockquote>
  <p>Take the first atom and count how many times it appears. Write the result down, and
reduce the list by removing this atom.</p>
</blockquote>

<p>This is not very “suitable” for recursion, or at least it is not very intuitive. There
must always be a base case and then a recursion. The right way to say it is:</p>

<blockquote>
  <p>Take the first atom, count how many times it appears, and write the result down. Repeat
for the reduced list.</p>
</blockquote>

<p><strong>Step 1.</strong> Take the first atom and count how many times it appears:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">;; PARTIAL: only once</span>
<span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nf">trace-first</span> <span class="nv">seq</span><span class="p">)</span>
  <span class="p">(</span><span class="nb">list</span> <span class="p">(</span><span class="nf">count-trace</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">seq</span><span class="p">)</span> <span class="nv">seq</span><span class="p">)</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">seq</span><span class="p">)))</span>

<span class="c1">;; (trace-first '(a b c a)) ;; '(2 a)</span>
</code></pre></div></div>

<p><strong>Step 2.</strong> Repeat for the reduced list. “Repeat” tells us to use recursion:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nf">trace-all</span> <span class="nv">seq</span><span class="p">)</span>
  <span class="p">(</span><span class="k">if</span> <span class="p">(</span><span class="nb">null?</span> <span class="nv">seq</span><span class="p">)</span>
      <span class="o">'</span><span class="p">()</span>
      <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nf">trace-first</span> <span class="nv">seq</span><span class="p">)</span>
            <span class="p">(</span><span class="nf">trace-all</span> <span class="p">(</span><span class="nf">remove</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">seq</span><span class="p">)</span> <span class="nv">seq</span><span class="p">)))))</span>

<span class="c1">;; (trace-all '(a a a c b e f c f g t t w w w w w g h))</span>
<span class="c1">;; '((3 a) (2 c) (1 b) (1 e) (2 f) (2 g) (2 t) (5 w) (1 h))</span>
</code></pre></div></div>

<p>You may not believe it, but that is all. Each result is consed onto the natural
recursion, as the Third Commandment from Part 1 says. So there is no accumulator and
nothing to reverse: the order is right from the start.</p>

<h2 id="polishing">Polishing</h2>

<p>Now a little polishing:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nf">trace-all</span> <span class="nv">seq</span><span class="p">)</span>
  <span class="p">(</span><span class="k">letrec</span>
      <span class="p">((</span><span class="nf">count-atom</span>
        <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">a</span> <span class="nv">lat</span><span class="p">)</span>
          <span class="p">(</span><span class="k">cond</span>
            <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="mi">0</span><span class="p">)</span>
            <span class="p">((</span><span class="nb">eq?</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">))</span> <span class="p">(</span><span class="nb">+</span> <span class="mi">1</span> <span class="p">(</span><span class="nf">count-atom</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">))))</span>
            <span class="p">(</span><span class="k">else</span>
             <span class="p">(</span><span class="nf">count-atom</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)))))))</span>
    <span class="p">(</span><span class="k">if</span> <span class="p">(</span><span class="nb">null?</span> <span class="nv">seq</span><span class="p">)</span>
        <span class="o">'</span><span class="p">()</span>
        <span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nf">atom</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">seq</span><span class="p">)))</span>
          <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">list</span> <span class="p">(</span><span class="nf">count-atom</span> <span class="nv">atom</span> <span class="nv">seq</span><span class="p">)</span> <span class="nv">atom</span><span class="p">)</span>
                <span class="p">(</span><span class="nf">trace-all</span> <span class="p">(</span><span class="nf">remove</span> <span class="nv">atom</span> <span class="nv">seq</span><span class="p">)))))))</span>

<span class="c1">;; (trace-all '(a a a c b e f c f g t t w w w w w g h))</span>
<span class="c1">;; '((3 a) (2 c) (1 b) (1 e) (2 f) (2 g) (2 t) (5 w) (1 h))</span>
</code></pre></div></div>

<p>And a bit more for the final result. In Part 1 I passed the counting function as a
parameter, so that we can also count in other ways. I keep that, and I hide the loop
itself:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nf">remove</span> <span class="nv">elm</span> <span class="nv">ls</span><span class="p">)</span>
  <span class="p">(</span><span class="k">cond</span>
    <span class="p">((</span><span class="nb">null?</span> <span class="nv">ls</span><span class="p">)</span> <span class="o">'</span><span class="p">())</span>
    <span class="p">((</span><span class="nb">equal?</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">ls</span><span class="p">)</span> <span class="nv">elm</span><span class="p">)</span> <span class="p">(</span><span class="nf">remove</span> <span class="nv">elm</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">ls</span><span class="p">)))</span>
    <span class="p">(</span><span class="k">else</span>
     <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">ls</span><span class="p">)</span> <span class="p">(</span><span class="nf">remove</span> <span class="nv">elm</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">ls</span><span class="p">))))))</span>

<span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nf">freq-*</span> <span class="nv">seq</span> <span class="nv">counter</span><span class="p">)</span>
  <span class="p">(</span><span class="k">letrec</span>
      <span class="p">((</span><span class="nf">freq</span>
        <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lat</span><span class="p">)</span>
          <span class="p">(</span><span class="k">if</span> <span class="p">(</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span>
              <span class="o">'</span><span class="p">()</span>
              <span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nf">atom</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)))</span>
                <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">list</span> <span class="p">(</span><span class="nf">counter</span> <span class="nv">atom</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">atom</span><span class="p">)</span>
                      <span class="p">(</span><span class="nf">freq</span> <span class="p">(</span><span class="nf">remove</span> <span class="nv">atom</span> <span class="nv">lat</span><span class="p">))))))))</span>
    <span class="p">(</span><span class="nf">freq</span> <span class="nv">seq</span><span class="p">)))</span>

<span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nf">count-freq</span> <span class="nv">seq</span><span class="p">)</span>
  <span class="p">(</span><span class="nf">freq-*</span> <span class="nv">seq</span> <span class="nv">count-trace</span><span class="p">))</span>

<span class="c1">;; (count-freq '(a a a c b e f c f g t t w w w w w g h))</span>
<span class="c1">;; '((3 a) (2 c) (1 b) (1 e) (2 f) (2 g) (2 t) (5 w) (1 h))</span>
</code></pre></div></div>

<p>The solution is now much cleaner and more professional. <code class="language-plaintext highlighter-rouge">remove</code> can stay a separate
function, because other functions will probably use it too. The counting function comes
as a parameter. The loop <code class="language-plaintext highlighter-rouge">freq</code> is different: it is a helper that is too specialized to
stand on its own. So I use this rule from
<a href="https://mitpress.mit.edu/9780262561006/the-seasoned-schemer/">The Seasoned Schemer</a>:</p>

<blockquote class="callout callout--commandment">
  <p><strong>The Thirteenth Commandment</strong></p>

  <p>Use <code class="language-plaintext highlighter-rouge">(letrec ...)</code> to hide and to protect functions.</p>
</blockquote>

<h2 id="learning-more">Learning More</h2>

<p>With this, I close the task. The result is quite good Scheme code.</p>

<p>Later, a reader pointed me to
<a href="https://www.cs.uni.edu/~wallingf/patterns/recursion.html">Roundabout</a>, a pattern
language for recursive programming by Eugene Wallingford, with examples in Scheme. It
gives names to the kinds of recursion in this task. <code class="language-plaintext highlighter-rouge">trace-all</code> is a <em>Structural
Recursion</em>: one case for each form of the list. <code class="language-plaintext highlighter-rouge">revert</code> and <code class="language-plaintext highlighter-rouge">revert-in</code> from Part 1 are
an <em>Interface Procedure</em> with an <em>Accumulator Variable</em>. And <code class="language-plaintext highlighter-rouge">freq</code>, hidden in <code class="language-plaintext highlighter-rouge">letrec</code>,
is a <em>Local Procedure</em>: it uses <code class="language-plaintext highlighter-rouge">counter</code> from <code class="language-plaintext highlighter-rouge">freq-*</code> directly, instead of passing it
on every call.</p>

<p>Here is a
<a href="https://www.youtube.com/watch?v=Ps8jOj7diA0&amp;list=PL9D558D49CA734A02">collection of lectures</a> that I
find very useful: Programming Paradigms (CS107) from Stanford, by Jerry Cain. For Scheme,
watch lectures 19 to 23. You will see how important <code class="language-plaintext highlighter-rouge">map</code> and <code class="language-plaintext highlighter-rouge">apply</code> are. Here is an
example from there:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">;;</span>
<span class="c1">;; Function: flatten-list</span>
<span class="c1">;; ----------------------</span>
<span class="c1">;; Flattens a list just like the original flatten does, but</span>
<span class="c1">;; it uses map, apply, and append instead of exposed car-cdr recursion.</span>
<span class="c1">;;</span>
<span class="p">(</span><span class="k">define</span> <span class="p">(</span><span class="nf">flatten-list</span> <span class="nv">ls</span><span class="p">)</span>
  <span class="p">(</span><span class="k">cond</span> <span class="p">((</span><span class="nb">null?</span> <span class="nv">ls</span><span class="p">)</span> <span class="o">'</span><span class="p">())</span>
        <span class="p">((</span><span class="nb">not</span> <span class="p">(</span><span class="nb">list?</span> <span class="nv">ls</span><span class="p">))</span> <span class="p">(</span><span class="nb">list</span> <span class="nv">ls</span><span class="p">))</span>
        <span class="p">(</span><span class="k">else</span> <span class="p">(</span><span class="nb">apply</span> <span class="nv">append</span> <span class="p">(</span><span class="nb">map</span> <span class="nv">flatten-list</span> <span class="nv">ls</span><span class="p">)))))</span>

<span class="c1">;; (flatten-list '(1 2 (3) 4)) ;; '(1 2 3 4)</span>
</code></pre></div></div>

<p>Not that hard, is it?</p>]]></content><author><name>Zlatozar Zhelyazkov</name></author><category term="Programming" /><category term="lisp" /><category term="scheme" /><category term="racket" /><category term="functional-programming" /><category term="recursion" /><category term="the-seasoned-schemer" /><summary type="html"><![CDATA[Part 2 of a Scheme exam task from FMI: better names for reduce and revert, what reverse costs, a natural recursion that needs no accumulator, and letrec from The Seasoned Schemer.]]></summary></entry><entry><title type="html">An FMI Exam Task in Scheme, Part 1</title><link href="https://zlatozar.github.io/fmi-task-part-1/" rel="alternate" type="text/html" title="An FMI Exam Task in Scheme, Part 1" /><published>2012-08-13T15:42:00+00:00</published><updated>2012-08-13T15:42:00+00:00</updated><id>https://zlatozar.github.io/fmi-task-part-1</id><content type="html" xml:base="https://zlatozar.github.io/fmi-task-part-1/"><![CDATA[<p>Two months ago someone showed me a task from a functional programming exam at FMI, the
Faculty of Mathematics and Informatics. Students had 2 hours to solve it. Here is roughly
how it looked:</p>

<blockquote>
  <p><strong>The task.</strong> Write a Scheme program that computes how often each atom appears in a
given list. Example:</p>

  <div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input:  '(a a b c)
Output: '((2 a) (1 b) (1 c))
</code></pre></div>  </div>
</blockquote>

<p>I had not written Scheme for at least four years, so I was not sure I could do it in time.
But it is a challenge, and I decided to refresh my memory: can I solve it within the same
2 hours?</p>

<p>I have read two books on the topic: <a href="https://htdp.org/">How to Design Programs</a> and
<a href="https://mitpress.mit.edu/9780262560993/the-little-schemer/">The Little Schemer</a>, formerly
known as <em>The Little LISPer</em>. The commandments and laws in the boxes below come from
<em>The Little Schemer</em>.</p>

<p>I use Emacs for everything except Java, so the natural choice was to set it up for Scheme.
There is not much choice, so I quickly set up <a href="https://www.nongnu.org/geiser/">Geiser</a>.
Things did not go well. I had forgotten a lot and had to debug, and Geiser did not help
me there. So <a href="https://racket-lang.org/">DrRacket</a> came to the rescue. It works very well.
The only problem: I could not make its key shortcuts work like Emacs, so I lost paredit.</p>

<p>To be honest, I did not finish the task within two hours. Here are my steps, mixed with my
reasoning.</p>

<h2 id="warming-up">Warming Up</h2>

<p>To warm up and to test my environment, I gave myself a smaller task:</p>

<blockquote>
  <p><strong>Warm-up.</strong> Check whether a given atom belongs to a given list. Example:</p>

  <div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>Input:  'a '(a b c)
Output: #t
</code></pre></div>  </div>
</blockquote>

<p>It was not hard:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">in-trace?</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">a</span> <span class="nv">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="k">cond</span>
      <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="no">#f</span><span class="p">)</span>
      <span class="p">((</span><span class="nb">eq?</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">))</span> <span class="no">#t</span><span class="p">)</span>
      <span class="p">(</span><span class="k">else</span>
       <span class="p">(</span><span class="nf">in-trace?</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">))))))</span>

<span class="c1">;; (in-trace? 'a '(a b c)) ;; #t</span>
</code></pre></div></div>

<blockquote class="callout callout--note">
  <p><strong>Note</strong></p>

  <p><code class="language-plaintext highlighter-rouge">(define (in-trace? a lat) ...)</code> is syntactic sugar for
<code class="language-plaintext highlighter-rouge">(define in-trace? (lambda (a lat) ...))</code>.</p>
</blockquote>

<blockquote class="callout callout--commandment">
  <p><strong>The Law of Car</strong></p>

  <p>The primitive <code class="language-plaintext highlighter-rouge">car</code> is defined only for non-empty lists.</p>
</blockquote>

<blockquote class="callout callout--commandment">
  <p><strong>The Law of Cdr</strong></p>

  <p>The primitive <code class="language-plaintext highlighter-rouge">cdr</code> is defined only for non-empty lists. The <code class="language-plaintext highlighter-rouge">cdr</code> of any non-empty list
is always another list.</p>
</blockquote>

<blockquote>
  <p><strong>Scheme style.</strong> Affix a question mark to the end of a name for a procedure whose
purpose is to ask a question of an object and to yield a boolean answer.</p>

  <p>Pronounce the question mark as if it were the isolated letter “p”. For example, to read
the fragment <code class="language-plaintext highlighter-rouge">(PAIR? OBJECT)</code> aloud, say: “pair-pee object.”</p>

  <p>— Taylor R. Campbell,
<a href="https://mumble.net/~campbell/scheme/style.txt">Riastradh’s Lisp Style Rules</a></p>
</blockquote>

<h2 id="the-algorithm-first">The Algorithm First</h2>

<p>The most important part, and the one I underestimated, is the algorithm itself. I did not
play it through with pen and paper first. I wrote code in a chaotic way. I was worried
about my Scheme knowledge, I wanted everything to be very cool, and I wanted to prove
myself. This slowed me down.</p>

<blockquote class="callout callout--commandment">
  <p><strong>The Sixth Commandment</strong></p>

  <p>Simplify [make it cool] only after the function is correct.</p>
</blockquote>

<p>This is the algorithm I chose:</p>

<blockquote>
  <p>Take the first atom and count how many times it appears. Write the result down. Then
reduce the list by removing this atom, and repeat. Example:</p>

  <div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(a a b c c) -&gt; (2 a)
(b c c)     -&gt; (1 b)
(c c)       -&gt; (2 c)
</code></pre></div>  </div>
</blockquote>

<h2 id="counting-one-atom">Counting One Atom</h2>

<p>This part was quick, and I learned some lessons:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">count-trace</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">a</span> <span class="nv">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="k">cond</span>
      <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="mi">0</span><span class="p">)</span>
      <span class="p">((</span><span class="nb">eq?</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">))</span> <span class="p">(</span><span class="nb">+</span> <span class="mi">1</span> <span class="p">(</span><span class="nf">count-trace</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">))))</span>
      <span class="p">(</span><span class="k">else</span>
       <span class="p">(</span><span class="nf">count-trace</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">))))))</span>

<span class="c1">;; (count-trace 'a '(a b a a a a c)) ;; 5</span>
</code></pre></div></div>

<blockquote class="callout callout--commandment">
  <p><strong>The Fourth Commandment (preliminary version)</strong></p>

  <p>Always change at least one argument while recurring. It must be changed to be closer to
termination. The changing argument must be tested in the termination condition: when
using <code class="language-plaintext highlighter-rouge">cdr</code>, test the termination with <code class="language-plaintext highlighter-rouge">null?</code>.</p>
</blockquote>

<p>I imagine recursion as a spiral. First it winds up, until the check <code class="language-plaintext highlighter-rouge">((null? lat) 0)</code>
stops it. Then it starts to unwind, and each call returns the value of its last line, the
expression around the recursive call. This is where the solution is built.</p>

<blockquote class="callout callout--commandment">
  <p><strong>The First Commandment (final version)</strong></p>

  <p>When recurring on a list of atoms, <code class="language-plaintext highlighter-rouge">lat</code>, ask two questions about it: <code class="language-plaintext highlighter-rouge">(null? lat)</code> and
<code class="language-plaintext highlighter-rouge">else</code>.</p>

  <p>When recurring on a number, <code class="language-plaintext highlighter-rouge">n</code>, ask two questions about it: <code class="language-plaintext highlighter-rouge">(zero? n)</code> and <code class="language-plaintext highlighter-rouge">else</code>.</p>

  <p>When recurring on a list of S-expressions, <code class="language-plaintext highlighter-rouge">l</code>, ask three questions about it:
<code class="language-plaintext highlighter-rouge">(null? l)</code>, <code class="language-plaintext highlighter-rouge">(atom? (car l))</code>, and <code class="language-plaintext highlighter-rouge">else</code>.</p>
</blockquote>

<h2 id="removing-an-atom">Removing an Atom</h2>

<p>The next step is to build the reduced list:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">reduce</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">a</span> <span class="nv">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="k">cond</span>
      <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="o">'</span><span class="p">())</span>
      <span class="p">(</span><span class="k">else</span> <span class="p">(</span><span class="k">cond</span>
              <span class="p">((</span><span class="nb">eq?</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">a</span><span class="p">)</span> <span class="p">(</span><span class="nf">reduce</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)))</span>
              <span class="p">(</span><span class="k">else</span> <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nf">reduce</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)))))))))</span>

<span class="c1">;; (reduce 'a '(a b c a)) ;; '(b c)</span>
</code></pre></div></div>

<p>Have you asked yourself what happens when no question in a <code class="language-plaintext highlighter-rouge">cond</code> is true? The result is
not specified. That is why every <code class="language-plaintext highlighter-rouge">cond</code> should end with <code class="language-plaintext highlighter-rouge">else</code>, and <code class="language-plaintext highlighter-rouge">else</code> should not
hide more questions inside it.</p>

<p>As in Common Lisp, <code class="language-plaintext highlighter-rouge">(cond ... (else ...))</code> can also be written as <code class="language-plaintext highlighter-rouge">(cond ... (#t ...))</code>.</p>

<p>I refactor at once. All questions go above <code class="language-plaintext highlighter-rouge">else</code>, and <code class="language-plaintext highlighter-rouge">else</code> keeps only what is left:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">reduce</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">a</span> <span class="nv">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="k">cond</span>
      <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="o">'</span><span class="p">())</span>
      <span class="p">((</span><span class="nb">eq?</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">a</span><span class="p">)</span> <span class="p">(</span><span class="nf">reduce</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)))</span>
      <span class="p">(</span><span class="k">else</span>
       <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nf">reduce</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)))))))</span>

<span class="c1">;; (reduce 'a '(a b c a)) ;; '(b c)</span>
</code></pre></div></div>

<h2 id="three-rules-about-cons">Three Rules About cons</h2>

<p>Here are three very important rules:</p>

<blockquote class="callout callout--commandment">
  <p><strong>The Second Commandment</strong></p>

  <p>Use <code class="language-plaintext highlighter-rouge">cons</code> to build lists.</p>
</blockquote>

<p>When I first read a book about Lisp, I thought <code class="language-plaintext highlighter-rouge">cons</code> was very easy. It turned out I was
not quite right. If you think so too, then why does this happen?</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nv">&gt;</span> <span class="p">(</span><span class="nb">cons</span> <span class="o">'</span><span class="p">(</span><span class="nf">1</span> <span class="mi">2</span><span class="p">)</span> <span class="o">'</span><span class="p">(</span><span class="nf">3</span> <span class="mi">4</span><span class="p">))</span>
<span class="p">((</span><span class="nf">1</span> <span class="mi">2</span><span class="p">)</span> <span class="mi">3</span> <span class="mi">4</span><span class="p">)</span>
</code></pre></div></div>

<p><strong>Hint:</strong> How is this represented in memory?</p>

<blockquote class="callout callout--key">
  <p><strong>The Golden Rule of cons</strong></p>

  <p>The second argument to <code class="language-plaintext highlighter-rouge">cons</code> should be a list, and every list ends with <code class="language-plaintext highlighter-rouge">'()</code>.</p>
</blockquote>

<p>Here are some explanations that I find useful:</p>

<blockquote>
  <p><code class="language-plaintext highlighter-rouge">cons</code> builds pairs, not lists! Lisp interpreters use a dot to separate the elements of
a pair visually. <code class="language-plaintext highlighter-rouge">car</code> and <code class="language-plaintext highlighter-rouge">cdr</code> return the first and the second element of a pair.</p>

  <p>Lists are built on top of pairs. If the <code class="language-plaintext highlighter-rouge">cdr</code> of a pair points to another pair, the
sequence is treated as a list.</p>

  <p>The <code class="language-plaintext highlighter-rouge">cdr</code> of the last pair points to a special object called null (written as <code class="language-plaintext highlighter-rouge">'()</code>).
It tells the interpreter that it has reached the end of the list.</p>

  <p>For example, the list <code class="language-plaintext highlighter-rouge">'(a b c)</code> is built by evaluating this expression:</p>

  <div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">cons</span> <span class="ss">'a</span> <span class="p">(</span><span class="nb">cons</span> <span class="ss">'b</span> <span class="p">(</span><span class="nb">cons</span> <span class="ss">'c</span> <span class="o">'</span><span class="p">())))</span>
<span class="c1">;; (a b c)</span>
</code></pre></div>  </div>

  <p>The <code class="language-plaintext highlighter-rouge">list</code> procedure is a shortcut for creating lists:</p>

  <div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nb">list</span> <span class="ss">'a</span> <span class="ss">'b</span> <span class="ss">'c</span><span class="p">)</span>
<span class="c1">;; (a b c)</span>
</code></pre></div>  </div>

  <p>Another way to think of sequences whose elements are sequences is as trees. The elements
of the sequence are the branches of the tree, and elements that are themselves sequences
are subtrees.</p>

  <p>— The last paragraph is from
<a href="https://mitp-content-server.mit.edu/books/content/sectbyfn/books_pres_0/6515/sicp.zip/full-text/book/book-Z-H-15.html">SICP, section 2.2.2</a></p>
</blockquote>

<blockquote class="callout callout--commandment">
  <p><strong>The Third Commandment</strong></p>

  <p>When building lists, describe the first typical element, and then <code class="language-plaintext highlighter-rouge">cons</code> it onto the
natural recursion.</p>
</blockquote>

<p>Here is what the last commandment means in <code class="language-plaintext highlighter-rouge">reduce</code>:</p>

<div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(else (cons (car lat) (reduce a (cdr lat))))
            |_______| |__________________|
             typical   natural recursion
                   (recur on the rest of lat)
</code></pre></div></div>

<h2 id="a-first-draft">A First Draft</h2>

<p>Hey, are we done?</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">freq</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lst</span><span class="p">)</span>
    <span class="p">(</span><span class="k">define</span> <span class="nv">freq-in</span>
      <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lat</span> <span class="nv">seen</span><span class="p">)</span>
        <span class="p">(</span><span class="k">cond</span>
          <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">seen</span><span class="p">)</span>
          <span class="p">(</span><span class="k">else</span>
           <span class="p">(</span><span class="nf">freq-in</span> <span class="p">(</span><span class="nf">reduce</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">lat</span><span class="p">)</span>
                    <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nf">count-trace</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">))</span> <span class="nv">seen</span><span class="p">))))))</span>
    <span class="p">(</span><span class="nf">freq-in</span> <span class="nv">lst</span> <span class="o">'</span><span class="p">())))</span>

<span class="c1">;; (freq '(a a a c b e f c f g t t w w w w w g h))</span>
<span class="c1">;; '((1 . h) (5 . w) (2 . t) (2 . g) (2 . f) (1 . e) (1 . b) (2 . c) (3 . a))</span>
</code></pre></div></div>

<p>I use an inner helper function, <code class="language-plaintext highlighter-rouge">freq-in</code>, so the caller does not see the extra <code class="language-plaintext highlighter-rouge">seen</code>
parameter. Not bad, right? But look at the output. There are two problems:</p>

<ol>
  <li>The atoms come out in reverse order. This is a very common problem in Lisp when you
collect results in an accumulator.</li>
  <li>The task asks for <code class="language-plaintext highlighter-rouge">(3 a)</code>, but I get <code class="language-plaintext highlighter-rouge">(3 . a)</code>: a pair, not a list. I broke the golden
rule of <code class="language-plaintext highlighter-rouge">cons</code>. The second argument was an atom, not a list.</li>
</ol>

<p>The second problem is easy to fix: <code class="language-plaintext highlighter-rouge">(list count atom)</code> instead of <code class="language-plaintext highlighter-rouge">(cons count atom)</code>. For
the first one I need a function that reverses a list:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">revert</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lst</span><span class="p">)</span>
    <span class="p">(</span><span class="k">define</span> <span class="nv">revert-in</span>
      <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lat</span> <span class="nv">rev</span><span class="p">)</span>
        <span class="p">(</span><span class="k">cond</span>
          <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">rev</span><span class="p">)</span>
          <span class="p">(</span><span class="k">else</span>
           <span class="p">(</span><span class="nf">revert-in</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">rev</span><span class="p">))))))</span>
    <span class="p">(</span><span class="nf">revert-in</span> <span class="nv">lst</span> <span class="o">'</span><span class="p">())))</span>

<span class="c1">;; (revert '(a b c)) ;; '(c b a)</span>
<span class="c1">;; (revert '((1 1) (2 2) (3 3))) ;; '((3 3) (2 2) (1 1))</span>
</code></pre></div></div>

<p>I did not write it quickly. This is how I reasoned:</p>

<blockquote>
  <p>I will use recursion, so I have to reduce the problem of reversing <code class="language-plaintext highlighter-rouge">(1 2 3 4)</code> with
<code class="language-plaintext highlighter-rouge">car</code> and <code class="language-plaintext highlighter-rouge">cdr</code>. Step by step, the two arguments of <code class="language-plaintext highlighter-rouge">revert-in</code> are:</p>

  <div class="language-text highlighter-rouge"><div class="highlight"><pre class="highlight"><code>(1 2 3 4)  ()
(2 3 4)    (1)
(3 4)      (2 1)
(4)        (3 2 1)
()         (4 3 2 1)
</code></pre></div>  </div>

  <p>I noticed that I always pass the <code class="language-plaintext highlighter-rouge">cdr</code> as the first argument, and let the second one
build the result with <code class="language-plaintext highlighter-rouge">cons</code>.</p>
</blockquote>

<h2 id="tracing-the-recursion-by-hand">Tracing the Recursion by Hand</h2>

<p>You may prefer another method: write out the recursion by hand. This example is from
<em>The Little Schemer</em>:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="c1">;; The rember function removes the first occurrence</span>
<span class="c1">;; of the given atom from the given list.</span>
<span class="p">(</span><span class="k">define</span> <span class="nv">rember</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">a</span> <span class="nv">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="k">cond</span>
      <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="o">'</span><span class="p">())</span>
      <span class="p">((</span><span class="nb">eq?</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">a</span><span class="p">)</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">))</span>
      <span class="p">(</span><span class="k">else</span> <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span>
                  <span class="p">(</span><span class="nf">rember</span> <span class="nv">a</span> <span class="p">(</span><span class="nb">cdr</span> <span class="nv">lat</span><span class="p">)))))))</span>

<span class="c1">;; (rember 'cup '(coffee mock cup tea cup hick)) ;; '(coffee mock tea cup hick)</span>
</code></pre></div></div>

<p>The hardest line is <code class="language-plaintext highlighter-rouge">((eq? (car lat) a) (cdr lat))</code>. How is the result list built?</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="nf">rember</span> <span class="ss">'cup</span> <span class="o">'</span><span class="p">(</span><span class="nf">coffee</span> <span class="nv">mock</span> <span class="nv">cup</span> <span class="nv">tea</span> <span class="nv">cup</span> <span class="nv">hick</span><span class="p">))</span>
<span class="nv">=</span> <span class="p">(</span><span class="nb">cons</span> <span class="ss">'coffee</span> <span class="p">(</span><span class="nf">rember</span> <span class="ss">'cup</span> <span class="o">'</span><span class="p">(</span><span class="nf">mock</span> <span class="nv">cup</span> <span class="nv">tea</span> <span class="nv">cup</span> <span class="nv">hick</span><span class="p">)))</span>
<span class="nv">=</span> <span class="p">(</span><span class="nb">cons</span> <span class="ss">'coffee</span> <span class="p">(</span><span class="nb">cons</span> <span class="ss">'mock</span> <span class="p">(</span><span class="nf">rember</span> <span class="ss">'cup</span> <span class="o">'</span><span class="p">(</span><span class="nf">cup</span> <span class="nv">tea</span> <span class="nv">cup</span> <span class="nv">hick</span><span class="p">))))</span>
<span class="c1">;; here (eq? (car lat) a) is true, so rember returns (cdr lat)</span>
<span class="nv">=</span> <span class="p">(</span><span class="nb">cons</span> <span class="ss">'coffee</span> <span class="p">(</span><span class="nb">cons</span> <span class="ss">'mock</span> <span class="o">'</span><span class="p">(</span><span class="nf">tea</span> <span class="nv">cup</span> <span class="nv">hick</span><span class="p">)))</span>
<span class="nv">=</span> <span class="o">'</span><span class="p">(</span><span class="nf">coffee</span> <span class="nv">mock</span> <span class="nv">tea</span> <span class="nv">cup</span> <span class="nv">hick</span><span class="p">)</span>
</code></pre></div></div>

<h2 id="the-final-solution">The Final Solution</h2>

<p>Feeling confident, I write the final solution, using this rule:</p>

<blockquote class="callout callout--commandment">
  <p><strong>The Eighth Commandment</strong></p>

  <p>Use help functions to abstract from representations.</p>
</blockquote>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">freq-final</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lst</span><span class="p">)</span>
    <span class="p">(</span><span class="k">define</span> <span class="nv">freq-in</span>
      <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lat</span> <span class="nv">seen</span><span class="p">)</span>
        <span class="p">(</span><span class="k">cond</span>
          <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nf">revert</span> <span class="nv">seen</span><span class="p">))</span>
          <span class="p">(</span><span class="k">else</span>
           <span class="p">(</span><span class="nf">freq-in</span> <span class="p">(</span><span class="nf">reduce</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">lat</span><span class="p">)</span>
                    <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">list</span> <span class="p">(</span><span class="nf">count-trace</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">))</span> <span class="nv">seen</span><span class="p">))))))</span>
    <span class="p">(</span><span class="nf">freq-in</span> <span class="nv">lst</span> <span class="o">'</span><span class="p">())))</span>

<span class="c1">;; (freq-final '(a a a c b e f c f g t t w w w w w g h))</span>
<span class="c1">;; '((3 a) (2 c) (1 b) (1 e) (2 f) (2 g) (2 t) (5 w) (1 h))</span>

<span class="c1">;; (freq-final '(a a b c)) ;; '((2 a) (1 b) (1 c))</span>

<span class="c1">;; (freq-final '()) ;; '()</span>
</code></pre></div></div>

<blockquote class="callout callout--note">
  <p><strong>Where to reverse</strong></p>

  <p>The first version of this post called <code class="language-plaintext highlighter-rouge">revert</code> around the recursive call. Then every
return reversed the list once more, and the order was right only when the number of
different atoms was odd. Both examples above have an odd number, so the bug stayed
hidden: <code class="language-plaintext highlighter-rouge">(a b)</code> gave <code class="language-plaintext highlighter-rouge">((1 b) (1 a))</code>. Reverse once, when the accumulator is complete.</p>
</blockquote>

<p>As a solution for an exam task, this is enough. But can we do something more? I have to
think!</p>

<p>This <code class="language-plaintext highlighter-rouge">count-trace</code> ties the function to one way of counting. We may want something else,
for example a <code class="language-plaintext highlighter-rouge">count-odd-trace</code>. So I pass the counting function as a parameter:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">freq-*</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lst</span> <span class="nv">func</span><span class="p">)</span>
    <span class="p">(</span><span class="k">define</span> <span class="nv">freq-in</span>
      <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lat</span> <span class="nv">seen</span><span class="p">)</span>
        <span class="p">(</span><span class="k">cond</span>
          <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nf">revert</span> <span class="nv">seen</span><span class="p">))</span>
          <span class="p">(</span><span class="k">else</span>
           <span class="p">(</span><span class="nf">freq-in</span> <span class="p">(</span><span class="nf">reduce</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">lat</span><span class="p">)</span>
                    <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">list</span> <span class="p">(</span><span class="nf">func</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">))</span> <span class="nv">seen</span><span class="p">))))))</span>
    <span class="p">(</span><span class="nf">freq-in</span> <span class="nv">lst</span> <span class="o">'</span><span class="p">())))</span>

<span class="c1">;; (freq-* '(a a b c) count-trace) ;; '((2 a) (1 b) (1 c))</span>
</code></pre></div></div>

<blockquote class="callout callout--commandment">
  <p><strong>The Ninth Commandment</strong></p>

  <p>Abstract common patterns with a new function.</p>
</blockquote>

<blockquote>
  <p><strong>From lambda calculus.</strong> One thing we do know how to do is: <em>we know how to get rid of
free variables.</em></p>

  <p>Think about it: why is <code class="language-plaintext highlighter-rouge">x</code> free in <code class="language-plaintext highlighter-rouge">(lambda (y) x)</code>? Because it does not look like this:
<code class="language-plaintext highlighter-rouge">(lambda (x) (lambda (y) x))</code>. Well, if we want it to look like that, let’s just make it
be that! After all, we are not changing the value of the expression, we are only
changing the way the free variable will derive its meaning.</p>

  <p><strong>We are promising to pass in the value rather than rely on the rules of lexical scoping
to ascribe the right value from the static (lexically apparent) context. This process of
factoring out free variables is called abstraction.</strong></p>
</blockquote>

<p><strong>Update:</strong> After reading
<a href="https://mitpress.mit.edu/9780262561006/the-seasoned-schemer/">The Seasoned Schemer</a>, I
saw that a <code class="language-plaintext highlighter-rouge">let</code> is handy here. A named <code class="language-plaintext highlighter-rouge">let</code> removes the repeated <code class="language-plaintext highlighter-rouge">(car lat)</code> and the
separate helper definition that only starts the loop:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">freq-*</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lst</span> <span class="nv">func</span><span class="p">)</span>
    <span class="p">(</span><span class="k">let</span> <span class="nv">freq-in</span> <span class="p">((</span><span class="nf">lat</span> <span class="nv">lst</span><span class="p">)</span> <span class="p">(</span><span class="nf">seen</span> <span class="o">'</span><span class="p">()))</span>
      <span class="p">(</span><span class="k">cond</span>
        <span class="p">((</span><span class="nb">null?</span> <span class="nv">lat</span><span class="p">)</span> <span class="p">(</span><span class="nf">revert</span> <span class="nv">seen</span><span class="p">))</span>
        <span class="p">(</span><span class="k">else</span>
         <span class="p">(</span><span class="k">let</span> <span class="p">((</span><span class="nf">curr</span> <span class="p">(</span><span class="nb">car</span> <span class="nv">lat</span><span class="p">)))</span>
           <span class="p">(</span><span class="nf">freq-in</span> <span class="p">(</span><span class="nf">reduce</span> <span class="nv">curr</span> <span class="nv">lat</span><span class="p">)</span>
                    <span class="p">(</span><span class="nb">cons</span> <span class="p">(</span><span class="nb">list</span> <span class="p">(</span><span class="nf">func</span> <span class="nv">curr</span> <span class="nv">lat</span><span class="p">)</span> <span class="nv">curr</span><span class="p">)</span> <span class="nv">seen</span><span class="p">))))))))</span>
</code></pre></div></div>

<blockquote class="callout callout--commandment">
  <p><strong>The Fifteenth Commandment (revised version)</strong></p>

  <p>Use <code class="language-plaintext highlighter-rouge">(let ...)</code> to name the values of repeated expressions in a function definition if
they may be evaluated twice for one and the same use of the function.</p>
</blockquote>

<p>With this abstraction, I can easily build other functions on top of it:</p>

<div class="language-scheme highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">(</span><span class="k">define</span> <span class="nv">count-freq</span>
  <span class="p">(</span><span class="k">lambda</span> <span class="p">(</span><span class="nf">lat</span><span class="p">)</span>
    <span class="p">(</span><span class="nf">freq-*</span> <span class="nv">lat</span> <span class="nv">count-trace</span><span class="p">)))</span>

<span class="c1">;; (count-freq '(a a b c)) ;; '((2 a) (1 b) (1 c))</span>
</code></pre></div></div>

<h2 id="do-we-get-a-six">Do We Get a Six?</h2>

<p>In Bulgaria, 6 is the highest grade. Do we get a 6? Yes, if the algorithm I chose is
correct and its complexity is not too high. The rule for judging it is:</p>

<blockquote>
  <p><strong>The asymptotic outlook.</strong> Ask not which takes longer, but rather which is more rapidly
taking longer as the problem size increases.</p>
</blockquote>

<p>I look at the final result and I do not like it. I wrote it by wandering around, even
though it is correct. No Lisp programmer would write it this way. It has no style; it is
just a set of rules put together. <a href="/fmi-task-part-2/">Part 2</a>
follows with the fixes.</p>]]></content><author><name>Zlatozar Zhelyazkov</name></author><category term="Programming" /><category term="lisp" /><category term="scheme" /><category term="racket" /><category term="functional-programming" /><category term="recursion" /><category term="the-little-schemer" /><summary type="html"><![CDATA[A functional programming exam task from FMI solved in Scheme: count how often each atom appears in a list, with recursion, cons, accumulators, and The Little Schemer commandments.]]></summary></entry></feed>