For Cleaner Domains, Move IO to the Edges of Your App

Cesar Aguirre - Sep 2 - - Dev Community

I originally posted an extended version of this post on my blog a long time ago in a galaxy far, far away.


Don't get too close with I/O.

That's how I'd summarize the talk "Moving IO to the edges of your app" by Scott Wlaschin at NDC London 2024.

In case you don't know Scott Wlaschin's work, he runs the site F# for Fun and Profit and talks about Functional Programming a lot. He's a frequent speaker at the NDC Conference.

Here's the YouTube video of the talk, in case you want to watch it.

These are the main takeaways from that talk.

I/O Is Evil: Keep It at Arm's Length

In a perfect world, all code should be pure. The same inputs return the same outputs with no side effects.

But we're not in a perfect world, and our code is full of impurities: retrieving the current time, accessing the network, and calling databases.

Instead of aiming for 100% pure code, the guideline is to move I/O (or impurities) away from the business logic or rules.

  ┌────────────────────────────────────┐  
  │  ┌─────┐    ┌────────┐    ┌─────┐  │  
──┼─►│ I/O ├───►│ Logic  ├───►│ I/O ├──┼─►
  │  └─────┘    └────────┘    └─────┘  │  
  └────────────────────────────────────┘  
                Unit Tests   
            ├────────────────┤            

            Integration Tests         
   ├──────────────────────────────────┤
Enter fullscreen mode Exit fullscreen mode

When we mix I/O with our domain logic, we make our domain logic harder to understand and test, and more error-prone.

So let's pay attention to functions with no inputs or no outputs. Often, they do I/O somewhere.

If you think we don't write functions with no outputs, let's take another look at our repositories.

Sure, our Create or Update methods might return an ID. But they're not deterministic. If we insert the same record twice, we get different IDs or even an error if we have unique constraints in our tables.

The guideline here is to write code that is:

  • Comprehensible: it receives what it needs as input and returns some output.
  • Deterministic: it returns the same outputs, given the same input.
  • Free of side effects: it doesn't do anything under the hood.

Just Return the Decision

This is the example shown in the talk:

Let's say we need to update a customer's personal information. If the customer changes their email, we should send a verification email. And, of course, we should update the new name and email in the database.

This is how we might do that,

async static Task UpdateCustomer(Customer newCustomer)
{
    var existing = await CustomerDb.ReadCustomer(newCustomer.Id); // 👈

    if (existing.Name != newCustomer.Name
        || existing.EmailAddress != newCustomer.EmailAddress)
    {
        await CustomerDb.UpdateCustomer(newCustomer); // 👈
    }

    if (existing.EmailAddress != newCustomer.EmailAddress)
    {
        var message = new EmailMessage(newCustomer.EmailAddress, "Some message here...");
        await EmailServer.SendMessage(message); // 👈
    }
}
Enter fullscreen mode Exit fullscreen mode

We're mixing the database calls with our decision-making code. IO is "close" to our business logic.

Of course, we might argue static methods are a bad idea and pass two interfaces instead: ICustomerDb and IEmailServer. But we're still mixing IO with business logic.

This time, the guideline is to create an imperative shell and just return the decision from our business logic.

Here's how to update our customers "just returning the decision,"

// This is a good place for discriminated unions.
// But we still don't have them in C#. Sorry!
public abstract record UpdateCustomerDecision
{
    public record DoNothing : UpdateCustomerDecision;
    public record OnlyUpdateCustomer(Customer Customer) : UpdateCustomerDecision;
    public record UpdateCustomerAndSendEmail(Customer Customer, EmailMessage Message) : UpdateCustomerDecision;
}

static UpdateCustomerDecision UpdateCustomer(Customer existing, Customer newCustomer)
{
    UpdateCustomerDecision result = new UpdateCustomerDecision.DoNothing();

    if (existing.Name != newCustomer.Name
            || existing.EmailAddress != newCustomer.EmailAddress) // 👈
    {
        result = new UpdateCustomerDecision.OnlyUpdateCustomer(newCustomer);
    }

    if (existing.EmailAddress != newCustomer.EmailAddress) // 👈
    {
        var message = new EmailMessage(newCustomer.EmailAddress, "Some message here...");

        result = new UpdateCustomerDecision.UpdateCustomerAndSendEmail(newCustomer, message);
    }

    return result;
}

async static Task ImperativeShell(Customer newCustomer)
{
    var existing = await CustomerDb.ReadCustomer(newCustomer.Id);

    var result = UpdateCustomer(existing, newCustomer);
    //           👆👆👆
    // Nothing impure here

    switch (result.Decision)
    {
        case DoNothing:    
            // Well, doing nothing...😴
            break;

        case UpdateCustomerOnly:
            await CustomerDb.UpdateCustomer(result.Customer); // 🤖
            break;

        case UpdateCustomerAndSendEmail:
            await CustomerDb.UpdateCustomer(result.Customer); // 🤖
            await EmailServer.SendMessage(result.Message);
            break;
    }
}
Enter fullscreen mode Exit fullscreen mode

With the imperative shell, we don't have to deal with database calls and email logic inside our UpdateCustomer(). And we can unit test it without mocks.

As a side note, UpdateCustomerDecision and UpdateCustomerResult are a simple alternative to discriminated unions. Think of discriminated unions like enums where each member could be an object of a different type.

In more complex codebases, ImperativeShell() would be like a use case class or command handler.

Pure Code Doesn't Talk to the Outside

When we push I/O to the edges, our pure code doesn't need exception handling or asynchronous logic. Our pure code doesn't talk to the outside world.

These are the three code smells the speaker shared to watch out for in our domain code:

  1. Is it async? If so, you're doing I/O somewhere
  2. Is it catching exceptions? Again, you're (probably) I/O somewhere
  3. Is it throwing exceptions? Why not use a proper return value?

If any of these are true, we're doing IO inside our domain. And we should refactor our code. "All hands man your refactoring stations."

Voila! That's one approach to have pure business logic, not the one and only approach.

Whether we follow Ports and Adapters, Clean Architecture, or Functional Core-Imperative Shell, the goal is to abstract dependencies and avoid "contaminating" our business domain.


Starting out or already on the software engineering journey? Join my free 7-day email course to refactor your coding career and save years and thousands of dollars' worth of career mistakes.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player