Functional Core, Imperative Shell: separate deciding from doing
11 min read
In the previous article I wrote about why reading code well matters. This one is about the other side: how to write code that is easy to read and check from the start. The rule I use for this website, and have used on real systems for years, is called Functional Core, Imperative Shell, or FCIS for short.
The idea in two sentences
- The core makes decisions. It is made of functions that take data in and return results. It doesn't read the database, call HTTP, send email, or ask the machine's clock what time it is.
- The shell does the work. It fetches data, hands it to the core for a decision, then saves or sends the result.
The direct consequence is that when you call a core function, you know the only thing that matters is the value it returns. It doesn't quietly write to the database, change someone else's variable, or touch anything outside itself. You can stop reading at the edge of the function instead of tracing what else it might have affected.
In company terms, the core is the policy: a written rule that says what to do in each situation. The shell is the staff member who pulls the files, opens the policy manual, and does what it says. The policy doesn't need to know which cabinet the files are in, and the staff member shouldn't invent policy on the job.
It sounds simple, but the effect is large. Here are some examples.
Example 1: a discount coupon
Marketing's requirement is: "Orders of 1,000 baht or more can use a coupon for 10% off. The coupon is valid until a set time." Code like this is common:
func Checkout(ctx context.Context, userID, code string) error {
cart, _ := db.LoadCart(ctx, userID)
coupon, _ := db.LoadCoupon(ctx, code)
total := cart.Total // float64
if coupon != nil && time.Now().Before(coupon.ExpiresAt) {
if total >= 1000 {
total = total * 0.9
}
}
db.SaveOrder(ctx, userID, total)
mailer.SendReceipt(ctx, userID, total)
return nil
}
It works. Now ask a few questions.
- How do you test that an expired coupon is rejected? You need a database, a fake mail sender, and either real time passing or some way to fake the machine's clock. So in practice, nobody writes that test.
- The rule "1,000 or more gets 10% off" is buried between database reads and an email. If marketing asks "how does the system calculate discounts right now?", a developer has to read the whole function before answering.
- It uses
float64for money, which one day gives you a total of 899.9999999 baht.
Now pull the decision out into the core:
// core: no database, no clock, just data in and a result out.
// Satang is an int64 count of satang (1/100 baht), so there are no rounding surprises.
func Discount(subtotal Satang, c Coupon, now time.Time) (Satang, error) {
switch {
case !now.Before(c.ExpiresAt):
return 0, ErrCouponExpired
case subtotal < c.MinSpend:
return 0, ErrBelowMinSpend
}
return subtotal * Satang(c.PercentOff) / 100, nil
}
The shell is left with one job: read, decide, write.
// shell: talks to the outside world, but makes no decisions of its own
func (h *Handler) Checkout(ctx context.Context, userID, code string) error {
cart, err := h.store.Cart(ctx, userID)
if err != nil {
return err
}
coupon, err := h.store.Coupon(ctx, code)
if err != nil {
return err
}
off, err := promo.Discount(cart.Subtotal, coupon, time.Now())
if err != nil {
return err
}
return h.store.SaveOrder(ctx, cart, off)
}
Notice that every if in the shell is an error check. No business rule is left in it.
Notice also that the current time (now) is passed in as a parameter. Testing becomes a
plain table: no database, not a single mock of the database or the clock, no waiting, and
it runs in a fraction of a second:
tests := []struct {
name string
subtotal Satang
now time.Time
want Satang
wantErr error
}{
{"meets minimum, 10% off", 150_000, beforeExpiry, 15_000, nil},
{"one satang short", 99_999, beforeExpiry, 0, ErrBelowMinSpend},
{"expires at that exact second", 150_000, expiry, 0, ErrCouponExpired},
}
Edge cases such as "one satang short" or "expires at that exact second" are where bugs hide. They are also the cases almost nobody tests when every test has to set up a database first.
There is a side benefit people often miss. Once the rule is a clear function, business questions come up on their own. When dividing by 100 leaves a fraction of a satang, do we round up or down? Is "1,000 or more" counted before or after shipping? Marketing should answer these, not a developer guessing. Each answer becomes a new row in the test table.
Example 2: order status
Most online shops have order statuses such as pending payment, confirmed, shipped and
cancelled. In many systems the status changes are scattered everywhere. The admin page has
UPDATE orders SET status = 'cancelled', the payment callback has another, and the
customer page has another.
Then one day someone adds a "Cancel" button to the customer page and forgets to check whether the order has already shipped. Customers can cancel, the system refunds them automatically, and the goods are already on the delivery truck.
FCIS fixes this by putting every status rule in one function:
func Next(s Status, e Event) (Status, error) {
switch {
case s == Pending && e == Pay:
return Confirmed, nil
case s == Pending && e == Cancel:
return Cancelled, nil
case s == Confirmed && e == Ship:
return Shipped, nil
case s == Confirmed && e == Cancel:
return Cancelled, nil
case s == Shipped && e == Deliver:
return Delivered, nil
}
return s, ErrInvalidTransition
}
Every part of the system that changes a status has to go through this function. The
customer's Cancel button gets ErrInvalidTransition as soon as the order has shipped,
and whoever wrote the button didn't need to remember the rule.
This function also reads almost like the table the operations manager drew on the whiteboard. If they ask "can an order be cancelled after it ships?", you can point right at it. When the business wants a new "returned" status, you change it here, add a few rows of tests, and the whole system follows the new rule at once.
Example 3: let the core return a decision instead of acting
Say the system reorders low-stock items from suppliers every night. Instead of a loop that checks stock and sends purchase orders as it goes, the core returns a plan as data:
type Reorder struct {
SKU string
Qty int
}
func PlanReorders(items []StockLevel, p Policy) []Reorder {
var plan []Reorder
for _, it := range items {
if it.OnHand < p.MinOnHand {
plan = append(plan, Reorder{SKU: it.SKU, Qty: p.Target - it.OnHand})
}
}
return plan
}
The nightly shell reads stock levels, calls PlanReorders, and sends purchase orders
according to the plan. It looks like you only moved code around, but you get these for
free:
- A preview page. Purchasing can see "what will the system order tonight?" by calling the same function without sending anything.
- Trying new policies. If management wants to know how much more you'd order with double the minimum stock, run it on yesterday's real data without touching production.
- An audit trail. Log the inputs and the plan, and you can always explain why that item was ordered that night.
All of this works because the plan is plain data, not tied to a database connection or any other state. Gary Bernhardt, who named FCIS, describes this as using values as the boundaries between parts of a system. Data like this can go into a log, onto a queue, to another goroutine, or across to another service, because it carries nothing with it but the data itself.
Example 4: a customer says the price was wrong
A customer calls to say they used a coupon yesterday and didn't get the full discount. If the discount rule is tied to the database and the clock, reproducing the problem is hard, because the data and the time have both moved on.
If Discount is a core function, you take the subtotal, the coupon and the order time from
the log and add them as a new row in the test table. The result matches what really
happened every time, because the same input always gives the same output. Once the bug is
fixed, that row stays in the tests, so the same problem can't come back.
Example 5: this website
The site you're reading is split the same way. Code in internal/core turns markdown into
articles, formats dates, and prepares the data each page shows. Code in internal/shell
reads files, talks to Redis and answers HTTP requests. Even preparing text for display can
live in the core, just as in the original screencast, where turning tweets into text on
screen is the core's job.
The important part is that the rule doesn't depend on anyone remembering it. A test checks that nothing in the core imports a package that does I/O. If someone (including an AI writing code for us) calls the database from the core, that test fails immediately. Architecture rules that are checked automatically last much longer than rules that only live in a document.
The core and the shell are tested differently
In his talk Boundaries, Gary Bernhardt points out that the two parts have opposite shapes:
- The core has many paths but few dependencies. Each business rule is an
if, so there are many cases to test. But because it needs no database or network, unit tests written as tables can cover every case, quickly, with no mocks. - The shell has few paths but many dependencies: the database, the network, files.
Because it has almost no business
ifs, a few integration tests that run the main path are enough.
The trouble with mixed code is that it has many paths and many dependencies in the same place. Testing every case means setting up a database for every case, which is slow enough that in the end nobody does it. FCIS doesn't reduce the number of cases to test. It moves them to where testing is cheapest and fastest.
And because the shell has so few ifs, questions like "what has the system done so far,
and in what order?" are easy to answer: there are only a few paths to follow.
What you get
| Rules mixed with I/O | Split with FCIS | |
|---|---|---|
| Maintenance | Rules spread over many files; fixing one place breaks another | Rules live in one place; a policy change is one function |
| Fewer mistakes | Tests need a database, so they rarely get written | Tests are tables, fast, and cover the edge cases |
| Easier to understand | You read all the I/O before you find the rule | The parameters tell you what data the rule uses |
| Fits the business | Rules are hidden in code and need a developer to explain them | The function is the policy; the test table is the shared set of examples |
One more point ties back to the previous article. When AI writes code for you, a core function is much easier to check, because you only look at what goes in and what comes out. You don't have to trace whether the code touched the database or sent something somewhere.
Start tomorrow
You don't need to rewrite the whole system. Start small:
- Find functions that have business
ifs and database calls ortime.Now()in the same place. Those are the ones to split. - Move the time, random values and outside data out into parameters.
- Let the core return a value, or a plan, instead of acting on it.
- Keep the shell as thin as possible: read, decide, write.
- Start with the rule that breaks most often, or the one the business asks about most.
FCIS doesn't make the shell disappear. But once every decision has moved into the core, the shell is left thin and boring, and boring code is usually code that's hard to break.
Sources
The name Functional Core, Imperative Shell comes from Gary Bernhardt, who introduced the idea in 2012.
- Functional Core, Imperative Shell, a Destroy All Software screencast published on 12 July 2012. Its example is a terminal Twitter client whose core manages tweets, syncs timelines, tracks the cursor and renders tweets as text, while the shell handles the keyboard, screen, database and network based on the values the core returns.
- Boundaries, his talk at SCNA 2012, which develops the same idea: using simple values as the boundaries between parts of a system. It also covers isolated testing without mocks, and concurrency.