← Functional, Object-Oriented and Domain-Driven Design, Combined
Version 2, 15 November 2026
The principles, one approach at a time
Three guides to the principles of object-oriented programming, functional programming and domain-driven design. Open a line to read it.
Object-oriented programming
By the question that each principle answers
52 pointsThis tree is the guide. Each group is one question about the approach, and the principles below it are the answer. Use it to learn the approach from start to end.
Objects: what the unit is
8 pointsThe unit is an object: data and the operations on that data, kept together, with an identity of its own.
Object
3 pointsAn object joins state, behaviour and identity in one unit.
State
State is the data that the object holds now: the amount, the donor, the status. In the classic style, the state changes during the life of the object. This is the main difference from the functional style.
Behaviour
Behaviour is the set of operations that the object can do. Programmers call them methods. “Receive payment” and “refund” are behaviours of a donation. The operations live with the data that they use.
Identity
Two objects with the same data are still two objects. Donation 4417 stays donation 4417 when its status changes. Identity lets an object change and remain the same object.
Class and instance
3 pointsA class is the plan. An instance is one object made from the plan.
Class
The class Donation says which data each donation has and which operations it can do. A person writes it one time.
Instance
Donation 4417 is one instance. A program can hold millions of instances of one class, each with its own state.
Constructor
The constructor is the operation that makes a new instance. A good constructor refuses to make an object in a wrong state, for example a donation with a negative amount. Then each object is valid from its first moment.
Messages
2 pointsObjects work together by requests. The object that receives a request decides how to answer it.
A call is a request
The caller says what it wants: “donation, receive this payment”. The object decides how to do it. The caller does not know the internal steps, and it must not depend on them.
The original idea
Alan Kay gave the style its name. He said that the main idea is messages between independent parts, like cells in a body or computers on a network. Classes and inheritance got more attention later than he intended.
Encapsulation: how an object protects itself
9 pointsAn object hides its data and lets other code use a small set of operations only, so each rule lives in one place.
Hidden state
3 pointsNo code outside the object can read or change its data directly.
Private data, public operations
The data fields are private. The only way in is through the public operations. The set of public operations is the interface of the object.
Freedom to change the inside
No outside code depends on the internal data. So you can change how the object stores its data, and nothing else breaks. This is the first practical benefit of the style: a change stays local.
A getter and a setter for each field is a leak
An object with “get status” and “set status” for each field hides nothing. Any code can put it in any state. It is a plain record with more steps, and its rules end up outside it.
Invariants
3 pointsAn invariant is a rule that is always true for the object. The object itself enforces it.
The rule lives inside
“A refund cannot be larger than the payment” is checked inside the refund operation. No caller can go around the check, because there is no other way to refund.
Valid at all times
Each operation starts from a valid object and leaves a valid object. So code that receives an object does not check it again.
The same goal as the functional style
The functional style gets the same safety from types that cannot hold a wrong state. The object style gets it from a guard in each operation. The type is checked before the program runs. The guard is checked while it runs.
Tell, do not ask
3 pointsGive an object an instruction. Do not take out its data and decide for it.
Tell
In the weak form, the caller reads the status and then sets a new status. The rule lives in the caller, and each caller must repeat it. In the strong form, the caller says “refund”, and the donation applies its own rule.
Weak: if donation.status is Received
set donation.status to Refunded
Strong: donation.refund()Speak only to near neighbours
An object uses the things that it holds directly. It does not reach through them. “Campaign, then owner, then address, then city” ties the caller to four structures. Ask the campaign for the city. The name of this rule is the Law of Demeter.
A full model, not an empty one
Sometimes the objects hold only data, and all the rules are in separate “service” code. Martin Fowler calls this an anemic domain model. It has the cost of objects and not the benefit. Agents write this form often when nobody stops them.
Substitution: how objects replace each other
11 pointsCode that depends on a contract, and not on one specific object, accepts each object that keeps the contract.
Interface
3 pointsAn interface is a contract: a named set of operations, with no statement of how they are done.
The contract
“Payment gateway” promises two operations: charge and refund. It says nothing about Stripe or PayPal.
Depend on the contract
The donation code asks for “a payment gateway”. Each object that keeps the contract fits. A test gives it a false gateway that takes no money.
Abstraction
To name a contract is to decide what is important and what is detail. A good abstraction lets you forget the detail safely. A bad abstraction hides a detail that you need.
Polymorphism
3 pointsOne request gives different behaviour, and the object that receives the request decides which.
One message, many forms
The caller says “charge”. A Stripe gateway and a PayPal gateway each do it in their own way. The code of the caller is the same for the two.
It replaces chains of conditions
Without it, the code says “if Stripe do this, if PayPal do that” in ten places. With it, each gateway holds its own behaviour. A new gateway is one new object, and no caller changes.
A late choice
The program chooses the real operation while it runs, from the kind of object that is there. The term is dynamic dispatch.
Inheritance
3 pointsA class can take the data and the behaviour of a parent class, and add or change parts. It is easy to use wrongly.
Is-a
“A recurring donation is a donation.” The child class gets all that the parent class has. This saves writing.
The substitution rule
A child must work in each place where the parent works, with no surprise for the caller. If a recurring donation refuses an operation that each donation must support, the tree of classes is wrong. This is the Liskov substitution principle, named for Barbara Liskov.
The fragile parent
A child depends on the inside of its parent. A change in the parent can break children that the author did not see. Deep trees of classes are a common cause of object code that nobody dares to change.
Composition
2 pointsAn object is built from other objects that it holds and uses. Prefer this to inheritance.
Has-a
“A donation has a payment method.” The donation holds a payment method object and passes work to it. The term for this is delegation.
Why it is the first choice
The parts connect only through their contracts, so each part can change alone. You can also replace a part while the program runs. The 1994 book Design Patterns gave the advice: favour composition over inheritance. It is still the rule.
Design rules: how to arrange many objects
15 pointsEach object has one job and few ties, and the important code depends on contracts, not on details.
Cohesion and coupling
2 pointsKeep together the things that change together. Keep the ties between parts few and narrow.
High cohesion
All the parts of one object serve one purpose. A donation object that also writes emails and log files has low cohesion.
Low coupling
An object knows little about the other objects. Then a change in one object causes few changes in the others. In an old system, coupling is the main cause of high cost.
The SOLID rules
5 pointsFive rules, collected by Robert Martin, that sum up good object design. The first letters give the name.
S: one responsibility
One object has one reason to change. Ask: which one person or department can ask for a change to this code? If the answer is two, divide the object.
O: open to extension, closed to change
You add behaviour with a new object. You do not edit code that works. Polymorphism is the tool.
L: substitution
A child type works in each place where its parent type works. The point “The substitution rule” below Inheritance explains it.
I: small interfaces
Many small contracts are better than one large contract. A caller must not depend on operations that it does not use.
D: depend on contracts
The important code is the business rules. The detail code is the database and the email service. The important code must not depend on the detail code. The two depend on a contract that the important code owns. This turns the usual direction around, so the name is dependency inversion.
Dependency injection
3 pointsAn object receives the things that it needs from outside. It does not make them.
Receive, do not make
The donation service does not make a Stripe gateway. It gets “a payment gateway” when the program builds it. The code that builds the service decides which gateway.
Ports and adapters
The business code defines the contracts that it needs. These are the ports. Each outside system gets an adapter that keeps one contract. A second name for this structure is hexagonal architecture. The combined style of version 1 keeps this object idea.
Easy to test, easy to replace
A test passes in a false gateway. A change of supplier is one new adapter. The business rules do not change in the two cases.
Design patterns
5 pointsA design pattern is a named solution to a problem that comes back often. The name is the value: two words replace a long explanation.
Strategy
A rule that changes becomes an object behind a contract. Example: the match rule (2 times, 3 times, up to a limit) is a strategy that a campaign holds.
Adapter
An adapter is a wrapper that makes an outside system fit your contract.
Observer
An object tells a list of listeners that something occurred, and it does not know who they are. Events in user interfaces use this pattern.
Factory
A factory is an object whose job is to make other objects, when that work is complex.
A caution
A pattern is an answer. Use it when you have its problem. Code that uses patterns to look professional is harder to read than plain code.
The trade: what you get and what you pay
9 pointsThe style buys parts that can change and be replaced behind their contracts. It costs hidden state and, often, too much structure.
What you get
3 pointsEach benefit comes from one fact: the inside of a part is hidden behind its contract.
A change stays local
When the inside of an object changes, its callers do not change. In a large system, this decides how much each change costs.
Parts can be replaced
A new payment supplier, a false part for a test, a second way to send a receipt: each is one new object behind a contract that exists.
The code can use the business names
Objects can have the names of real things: donor, campaign, pledge. This is the bridge to domain-driven design.
What you pay
3 pointsThe costs come from state that changes and from too much structure.
Hidden state that changes
The result of an operation depends on what occurred before. To understand a defect, you must know the history of the object. A test must first bring each object to the correct state.
Shared objects
Two parts can hold the same object. If one part changes it, the other part sees the change with no warning. In parallel work this needs locks, and it causes defects that are hard to find.
Too many layers
Deep trees of classes, contracts with one implementation, factories that make factories. The structure hides the behaviour.
Where it fits
3 pointsIt fits systems made of many parts that can replace each other. It fits pure calculation less well.
A good fit
Systems with many kinds of parts that can replace each other: user interfaces, plug-ins, devices, connections to outside services. Also things with a long life and an identity.
A poor fit
Pure calculation and the transformation of data. There, an object adds ceremony, and a function is clearer.
Languages
Java, C#, Kotlin, Swift, Python, Ruby, TypeScript and C++. Most of them now also support the plain functional parts, so teams mix the two styles.
Object-oriented programming builds a program from objects. Each object holds its own data, protects it behind a small set of operations, and can replace a different object that offers the same operations.
The two trees hold the same 17 principles and the same 52 points. The first tree is the guide. The second tree puts the principles in the order of need.
Limits: the first tree divides the approach by the question that the principles answer. Its last group, the trade, holds judgements and not principles. The second tree uses one attribute, the grade of need. The grade is the author's judgement, and a principle moves when the grade changes. Its first group holds 9 principles, in the order of the guide. One point, the L of SOLID, refers to a point below Inheritance.
Functional programming
By the question that each principle answers
36 pointsThis tree is the guide. Each group is one question about the approach, and the principles below it are the answer. Use it to learn the approach from start to end.
Functions: how it calculates
9 pointsA function is a fixed calculation: the same input gives the same output, and small functions join into larger functions.
Pure function
3 pointsA pure function takes input, returns output, and does nothing else. It is the main unit of the style.
Same input, same output
The result depends on the input only. It does not depend on the time, on a database, or on a value that is stored in a different place. Example: the match for a donation of 100 dollars with a 2 times match is always 200. You check it one time, and you can trust it each time.
No side effect
The function changes nothing outside itself. It does not save, send or print, and it does not change its input. A side effect is a change that stays after the function ends. So you can repeat a call to a pure function, skip it, or run it in a different order, and nothing breaks.
A call is equal to its result
Because of the two rules above, you can replace a call with its result, and the program does the same thing. The term is referential transparency. For this reason a person, or an agent, can read one function alone and understand it fully.
Functions as values
3 pointsA function is a value, like a number. You can store it, give it to a different function, and return it.
Give a function as input
A function can take a rule as input. Example: “sort these donations” takes a second input, the rule that says which donation comes first. One sort function then serves each order.
Map, filter, reduce
These are the three most common functions that take a rule. Map changes each item. Filter keeps the items that pass a test. Reduce joins all the items into one value.
total received =
donations
keep each one where status is Received (filter)
take the amount of each one (map)
add all the amounts (reduce)Return a function
A function can build a new function. Example: “matcher for 2 times” returns a function that doubles an amount. The setting stays inside the new function. The term for the kept setting is a closure. The term for the technique is partial application.
Composition
3 pointsSmall functions join end to end into larger functions. This is how the style builds large behaviour.
The pipeline
The output of one function is the input of the next function. A decision reads as a row of steps: validate, then calculate the match, then make the receipt. Each step is small and has a name.
Say what, not how
The code names the result that you want, and not the steps of the machine. “Keep the received donations” is clearer than a loop with a counter. The term is declarative style. The style prefers an expression that returns a value to a statement that changes something.
Recursion in place of loops
A loop needs a counter that changes. A pure style has no values that change, so a function calls itself on a smaller part of the problem. In practice, map, filter and reduce hide the recursion, and you see it rarely.
Data: how it holds information
9 pointsA value does not change after it is made, and the types permit only the values that have a meaning.
Immutable data
3 pointsA value does not change after it is made. A change makes a new value.
A change makes a new value
To mark a donation as received, the code does not edit the donation. It makes a new donation value with the status Received. The old value stays as it was, for each part of the program that holds it.
Safe to share
Two parts of a program can hold the same value, and neither part can damage it for the other. This removes a full class of defects. It also makes parallel work safe, because no part must wait for a lock.
A copy has a low cost
A new value does not copy all of the old value. It points to the parts that did not change and stores the difference only. So immutable data uses less memory than you expect. The term is structural sharing.
Types that describe choices
3 pointsA type lists exactly the values that can exist. A wrong state then cannot be written.
AND types and OR types
An AND type holds some fields together: a donation has an amount AND a donor. An OR type is one case from a fixed list: a donation is Pledged OR Received OR Refunded. The formal names are product type and sum type. Together they are algebraic data types.
A wrong state cannot exist
Give each case only the fields that it can have. A pledged donation has no payment date. A received donation always has one. “A received donation with no payment date” cannot be written, so it needs no test and no check. The usual phrase is: make illegal states unrepresentable.
Donation is one of:
Pledged (amount, donor)
Received (amount, donor, payment date)
Refunded (amount, donor, payment date, refund date)Each case gets an answer
Code that reads an OR type must give an answer for each case. If a person adds a fourth case, the compiler shows each place that does not handle it. The technique is pattern matching. The check is the exhaustiveness check.
Absence and failure as values
3 pointsA value that is absent, and an operation that fails, are ordinary return values that the type shows.
Maybe, in place of null
A function that can find nothing returns a Maybe: “a value” or “nothing”. The caller must handle the two cases. This replaces null, the empty reference that causes a failure when a person forgets to check it. Some languages call the type Option.
Result, in place of an exception
A function that can refuse returns a Result: “OK, with the value” or “an error, with the reason”. A business refusal, such as “this donation is already refunded”, is then a usual answer, and the caller cannot ignore it. Exceptions stay for technical failures, such as a lost connection.
A chain that stops at the first error
Steps that each return a Result join into a chain. The chain continues while each step is OK, and it stops at the first error. Scott Wlaschin calls this railway oriented programming: one track for success and one track for failure.
Effects: how it meets the outside world
9 pointsAll reading, saving and sending goes to a thin layer at the edge, and the decisions stay pure.
Core and shell
3 pointsThe pure decisions are the core. A thin shell around the core reads, saves and sends.
What an effect is
An effect is each contact with the world outside the calculation: read a database, save a record, send an email, read the clock, get a random number. Effects are necessary. A program with no effects does nothing useful. The style does not remove them. It gives them one place.
Load, decide, save
The shell loads the data, calls the core for the decision, then saves and sends the result. The core does not call the database.
shell:
donation = load donation 4417 (effect)
event = decide(donation, "receive") (pure core)
save the new state (effect)
publish the event (effect)A test needs no setup
To test the core, you give it values and compare the answer. You need no database, no network and no clock. Hundreds of tests run in one second. Only the thin shell needs slow tests with real systems.
State through time
3 pointsState is a value that goes into a function, and a new value that comes out.
State in, new state out
A pure function cannot remember. So the state now is an input, and the next state is an output.
next state = step(state now, what occurred)
State as the sum of the events
If you keep the list of all the events, the state now is the result of a reduce on that list from the start. This is the base of event sourcing. You get a full history and you can replay it. You pay with more storage work, so use it for a named need only.
Parallel work with no shared state
Parallel work fails when two workers change one value. If no value changes, that problem cannot occur. For this reason the style is common in systems with many parallel requests.
Effects as descriptions
3 pointsThe deeper functional languages make an effect a value: a description of what to do, which the edge runs later.
A description, not an action
The core returns “send this email” as data. It does not send. The shell reads the description and does the work. So the choice of the effect is also pure, and a test can check it.
The type shows the effect
In Haskell and similar languages, the type of a function shows if it can do an effect. A function with no such mark is pure, and the compiler proves it. An agent cannot hide a database call inside a calculation.
Monad, in plain words
A monad is a wrapper around a value, with one rule for how to join steps that each return the wrapper. Maybe, Result, a list and an effect are all monads. The word is famous because the idea is abstract. You can use the pattern for years and not need the word.
The trade: what you get and what you pay
9 pointsThe style buys code that is easy to test and to reason about. It costs a learning curve and friction with common tools.
What you get
3 pointsEach benefit comes from one fact: a function depends on its input only.
Local reasoning
To understand a function, you read that function. Nothing in a different place can change its behaviour. This matters more with an agent, because an agent reads a small part of the code at one time.
A safe change
To change a pure function, you look at its inputs and its outputs. There is no hidden user of a shared value that can break.
Replay and audit
With events and pure decisions, you can run old inputs again and get the same answers. A defect report becomes a test.
What you pay
3 pointsMost of the cost is in people and tools, not in the machine.
A learning curve
The vocabulary comes from mathematics, and many guides start from theory. A team that knows only objects needs months, not days.
Friction with common tools
Most web frameworks and database tools expect objects that change. The shell must translate between the two worlds. That is real code to write and to keep.
Abstraction for its own sake
The style attracts people who like theory. The code can become a puzzle of small general functions that nobody can read. The rule: use the plain parts (pure functions, immutable data, OR types), and stop when the next step does not solve a named problem.
Where it fits
3 pointsIt fits rules and calculation. It fits code that is mostly effects less well.
A good fit
Rules, calculations, the transformation of data, money, parallel work. Each place where a wrong answer costs more than a slow delivery.
A poor fit
Code that is mostly effects: screens, the control of devices, simple forms on a database. There is little to keep pure, so the division adds work and no safety.
Languages
Haskell, OCaml, F#, Elixir, Clojure and Scala are made for the style. TypeScript, Kotlin, Swift, Rust, Python, and modern Java and C# support the plain parts well. You do not need a functional language to use the main ideas.
Functional programming builds a program from calculations that have no hidden effects, on data that does not change. It moves all contact with the outside world to the edge of the program.
The two trees hold the same 12 principles and the same 36 points. The first tree is the guide. The second tree puts the principles in the order of need.
Limits: the first tree divides the approach by the question that the principles answer. Its last group, the trade, holds judgements and not principles. The second tree uses one attribute, the grade of need. The grade is the author's judgement, and a principle moves when the grade changes. Its first group holds 7 principles, in the order of the guide.
Domain-driven design
By the question that each principle answers
53 pointsThis tree is the guide. Each group is one question about the approach, and the principles below it are the answer. Use it to learn the approach from start to end.
The domain: which problem the software solves
7 pointsThe business problem comes first, and the team puts its best effort only where the business is different from other businesses.
Domain and subdomains
3 pointsThe domain is the business area that the software serves. It divides into three kinds of part with different value. The division shows where careful design pays: deep design on a generic part is waste, and simple record-keeping on the core is a risk.
Core
The core is the part that makes the business different and wins customers. For a platform of matched donations, it is the matching rules and the campaign mechanics. Put the best people here, and build it yourself.
Supporting
A supporting part is necessary and specific to you, but customers do not choose you for it. Example: the tool that the customer success team uses to set up a campaign. Build it simply.
Generic
A generic part is one that each business has, and that is already solved: payments, login, the delivery of email. Buy it or use a standard service.
The model
4 pointsA model is a chosen simplification of the business, which the team and the code share.
A simplification with a purpose
A model is not a copy of reality. A subway map does not show the streets, and for that reason it is useful. The model keeps what the software needs for its decisions and drops the remainder.
Built with the domain experts
The people who do the business work know the rules and the exceptions. Developers and agents do not. The model comes from the talk between the two groups. Eric Evans calls this knowledge crunching.
Event storming
Event storming is a workshop method by Alberto Brandolini. Business people and developers put the events of the business on a wall, in the order of time: “pledge made”, “payment received”, “match applied”. The borders and the words come out of the wall.
The model is the code
There is no separate design document that the code then ignores. If the model changes, the code changes, and the reverse. Evans calls this model-driven design.
Language and borders: what the words mean, and where
13 pointsOne word has one meaning inside a border, and a map shows how the borders connect.
Ubiquitous language
4 pointsThe team uses one set of words in all places: in talk, in documents and in the code.
One word, one meaning
If the business says “pledge”, the code says Pledge, and not “PendingDonationRecord”. There is no translation between the business person and the code.
The business can read the code
A domain expert can read “when a pledge is received, apply the match” and say if it is correct. Mistakes show early.
A change of words is a change of the model
Sometimes the experts start to separate “pledge” from “commitment”. That is a discovery about the business, and the code must follow. Words that are not clear are a sign of a model that is not clear.
For an agent, the language is the brief
An agent that gets the exact words and their definitions guesses less. This is the point on which the writers in the research of version 1 agree most.
Bounded context
4 pointsA bounded context is a border. Inside it, each word has exactly one meaning, and one model applies.
The same word, two meanings
In Fundraising, a donor is a person with a history of gifts and a relationship. In Payments, a donor is a card and a billing address. The two are correct. One model for the two becomes large and wrong for each.
One model for each context
Each context has its own model, its own code and, in most cases, its own data. Inside the border, the language is strict.
The border is also a team border
One team owns one context. A context is also a natural unit of work for an agent: a small area with a complete vocabulary.
A context is not a subdomain
A subdomain is a part of the business problem. A context is a part of the solution. In a clean design, the two match one to one. In old systems, they frequently do not.
Context map
5 pointsThe context map shows each pair of contexts that exchange data, and who has the power in each pair.
Partnership, and customer with supplier
In a partnership, two teams plan together. In a customer and supplier relation, one team supplies, and the other team can ask for changes.
Conformist
The other side does not change for you: a large vendor, or an old system. You accept its model as it is.
Anticorruption layer
You do not accept the other model. A translation layer at your border changes its words into your words, so its concepts do not enter your core. Use it for old systems and for outside services. In object terms, it is an adapter.
Published language and open host
A context gives one documented, stable format to all its users, such as a public interface. The users connect to the format and not to the inside.
Shared kernel, and separate ways
Two contexts can share one small model that the two own. The cost: each change needs the two teams. Or the teams decide not to connect at all. That choice has the name separate ways.
Building blocks: what a model is made of
16 pointsInside one border, the model is made of values, things with an identity, clusters that change as one unit, and facts about what occurred.
Value object
3 pointsA value object is defined by its content only. It has no identity, and it does not change.
Defined by its content
“100 dollars” is equal to each other “100 dollars”. Money, a range of dates, an email address and a match ratio are value objects.
It carries its own rules
An email address value cannot be made from text with no “@”. After the value exists, all code can trust it. This removes checks that code otherwise repeats in many places.
Prefer values
Most concepts in a model can be values. They are the safest part: no identity, no change, easy to test. Here domain-driven design and the functional style agree fully.
Entity
2 pointsAn entity is defined by its identity. The identity stays the same while the data changes.
Identity before content
Donation 4417 is the same donation after its status and its amount change. Two donations with the same amount and the same donor are still two donations.
A life cycle
An entity is made, goes through defined states, and ends: Pledged, then Received, then possibly Refunded. The model says which steps are permitted.
Aggregate
6 pointsAn aggregate is a small cluster of entities and values that changes as one unit and guards its own rules.
One root
One entity is the entrance. It is the aggregate root. Outside code speaks to the root only. Example: a campaign with its matching pool. Nobody changes the pool directly.
It guards the invariants
A rule that must be true at all times, such as “the total match is never more than the pool”, lives inside one aggregate. The aggregate is the unit that can promise it.
One change, one save
A business operation changes one aggregate and saves it in one transaction. All of it is saved, or none of it.
Refer to other aggregates by ID
A donation holds the ID of its campaign, and not the campaign object. This keeps each aggregate small and independent.
Keep it small
The most common mistake is a large aggregate that pulls in half of the model. Then each change locks much data. Vaughn Vernon's rule: design small aggregates.
Between aggregates, consistency comes later
A rule that covers two aggregates is not saved in one step. The first aggregate publishes an event, and the second reacts a moment later. The term is eventual consistency. The business must agree that a short delay is acceptable.
Domain event
3 pointsA domain event is a record of a fact that occurred in the business, with a name in the past tense.
A fact, in the past tense
PaymentReceived, MatchApplied, DonationRefunded. A fact does not change. If it was wrong, a new event corrects it.
How the parts stay independent
The Donations context publishes PaymentReceived. Receipts and Reporting react. Donations does not know them. A new reaction needs no change in Donations.
Command and event
A command is a request, and the model can refuse it: “receive payment”. An event is the result, and nobody can refuse it, because it occurred. The combined style of version 1 uses this pair: a command and a state go in, and an event comes out.
Domain service
2 pointsA domain service holds a business rule that does not belong to one entity or one value.
A rule between objects
“Calculate the match for this donation, with the rules of this campaign and the pool that remains” uses three things. It is an operation of its own, with a business name.
Not a place for all the rules
If all the rules move into services, the entities become empty data. That is the anemic model again.
Isolation: how the model stays free of technology
8 pointsThe model knows nothing about databases, screens or outside services. Thin layers around it do that work.
Repository and factory
2 pointsA repository stores and finds aggregates, and a factory makes them. The two hide the technical work.
Repository
To the model, a repository looks like a collection: “give me donation 4417”, “save this donation”. The database work is behind it. There is one repository for each aggregate.
Factory
When it is complex to make an aggregate, a factory does the work and returns a valid aggregate.
Layers
4 pointsThe domain model is the centre, and it depends on nothing technical.
Domain layer
The model: values, entities, aggregates, events and domain services. It holds business rules only.
Application layer
One thin operation for each use case. It loads the aggregate, calls the model, saves, and publishes the events. It holds no business rule. This is the shell of version 1.
Infrastructure layer
The database, the email service, the payment gateway. Each one is behind a contract that the domain defines.
The dependency rule
The outer layers know the model. The model does not know them. This idea has three names: hexagonal architecture, onion architecture and clean architecture.
Patterns that people use with it
2 pointsPeople often name two patterns together with domain-driven design. The two are optional.
Separate models to write and to read
The model that changes data is not the model that answers questions. Changes go through the aggregates. Questions use simple views, one for each screen. The short name is CQRS.
Event sourcing
Store the events as the record, and calculate the state from them. You get the full history. It is hard to reverse, so use it for a named need only.
The trade: what you get and what you pay
9 pointsThe approach buys software that follows the business. It costs time with the experts, and it is too heavy for simple systems.
What you get
3 pointsThe software and the business describe the same thing in the same words.
Fewer misunderstandings
The business person and the code use one vocabulary. A wrong rule shows in a talk, before it becomes a defect.
A change follows the business
When a business rule changes, one place in the code holds that rule, with the business name.
Clear borders for teams and agents
Each context is small, and its vocabulary is complete. A team, or an agent, can hold it in mind.
What you pay
3 pointsThe cost is the time of the experts and the weight of the method.
It needs the experts
Without regular time from the people who know the business, the model is a guess with formal names.
Too heavy for simple record-keeping
A system that creates, reads, updates and deletes records, with few rules, needs none of this. Evans says to use the method for the complex core only.
Building blocks with no strategy
Many teams use entities and repositories, and they skip the language and the borders. They get the cost and not the value. The language, the contexts and the core are the parts that matter most.
Where it fits
3 pointsIt fits a complex business with a long life. It does not fit a simple or technical system.
A good fit
Complex business rules, more than one team, a long life, and experts who are available.
A poor fit
A prototype, a technical tool, a simple system for data entry.
It is not a programming style
It does not say “objects” or “functions”. Evans wrote the 2003 book with objects. Scott Wlaschin's 2018 book does the same work with functions. For this reason it combines with the two styles.
Domain-driven design says that the hard part of software is the business problem. So the code uses the words of the business, inside borders where each word has one meaning.
The two trees hold the same 16 principles and the same 53 points. The first tree is the guide. The second tree puts the principles in the order of need.
Limits: the first tree divides the approach by the question that the principles answer. Its last group, the trade, holds judgements and not principles. The second tree uses one attribute, the grade of need. The grade is the author's judgement, and a principle moves when the grade changes. Its first group holds 9 principles, in the order of the guide.
About this page
The three approaches answer three different questions. Object-oriented programming says how to pack the parts and hide the details. Functional programming says how to calculate a decision. Domain-driven design says what to model and where the borders are. Version 1 of this topic shows how the three fit in one small system. This version explains each approach alone, in 45 principles and 141 points.
How to read it
Each guide is one outline with three levels: groups, principles, and the points of each principle. The box with the plus opens a line. The small circle with the letter i shows what a line means. The four buttons at the top open one level in the first tree of each guide. The last button shows all the text of the lines that are open, so that the guide reads as a document.
Each guide has two trees with the same content. The first tree is the guide. The second tree puts the principles in three grades of need, for a person who directs coding agents and does not write code. Start with the first group of the second tree if you have little time.
The guides have no program code. A small number of points have pseudocode: plain words in the shape of code. The examples come from one small business, a platform for matched donations, which version 1 also uses.
The order of the guides
Object-oriented programming is first, because most people who wrote software in the past learned it first. Functional programming is second, because its main ideas are easier to see as a contrast with objects. Domain-driven design is last, because it is a design method and not a programming style, and it uses terms from the other two.
Sources
The guides sum up standard material. These are the primary sources for the principles that have a named author.
Object-oriented programming
- Alan Kay, on the meaning of object-oriented programming (2003)
- Martin Fowler, Tell Don't Ask
- Martin Fowler, Anemic Domain Model
- Robert Martin, Design Principles and Design Patterns (2000)
- Alistair Cockburn, Hexagonal Architecture
Functional programming
- John Hughes, Why Functional Programming Matters (1990)
- Yaron Minsky, Effective ML Revisited: make illegal states unrepresentable
- Scott Wlaschin, Railway Oriented Programming
- Gary Bernhardt, Boundaries (2012)
Domain-driven design
- Eric Evans, Domain-Driven Design Reference (2015)
- Martin Fowler, Bounded Context
- Vaughn Vernon, Effective Aggregate Design (2011)
- Alberto Brandolini, EventStorming
- Scott Wlaschin, Domain Modeling Made Functional
Books with no free copy: Eric Evans, Domain-Driven Design (2003). Gamma, Helm, Johnson and Vlissides, Design Patterns (1994). Vaughn Vernon, Implementing Domain-Driven Design (2013).