By Arham Jain

Is your code a tangled mess of business logic and side effects? Mixing database calls, network requests, and other external interactions directly with your core logic can lead to code that’s difficult to test, reuse, and understand. Instead, consider writing a functional core that’s called from an imperativ​​e shell.

Diagram of functional core, imperative shell

Separating your code into functional cores and imperative shells makes it more testable, maintainable, and adaptable. The core logic can be tested in isolation, and the imperati​​ve shell can be swapped out or modified as needed. Here’s some messy example code that mixes logic and side effects to send expiration notification emails to users:

// Bad: Logic and side effects are mixed

function sendUserExpiryEmail(): void {

  for (const user of db.getUsers()) {

    if (user.subscriptionEndDate > Date.now()) continue;

    if (user.isFreeTrial) continue;

    email.send(user.email, "Your account has expired " + user.name + “.”);

  }

}

A functional core should contain pure, testable business logic, which is free of side effects (such as I/O or external state mutation). It operates only on the data it is given.

An imperative shell is responsible for side effects, like database calls and sending emails. It uses the functions in your functional core to perform the business logic.

Rewriting the above code to follow the functional core / imperative shell pattern might look like:

Functional core

function getExpiredUsers(users: User[], cutoff: Date): User[] {

  return users.filter(user => user.subscriptionEndDate <= cutoff && !user.isFreeTrial);

}

function generateExpiryEmails(users: User[]): Array<[string, string]> {

  return users.map(user => 

    ([user.email, “Your account has expired “ + user.name + “.”])

  );

}

Imperative shell

email.bulkSend(generateExpiryEmails(getExpiredUsers(db.getUsers(), Date.now())));

Now that the code is following this pattern, adding a feature to send a new type of email is as simple as writing a new pure function and reusing getExpiredUsers:

// Sending a reminder email to users

function generateReminderEmails(users: User[], cutoff: Date): Array<[string, string]> {...}

const fiveDaysFromNow = ...

email.bulkSend(generateReminderEmails(getExpiredUsers(db.getUsers(), fiveDaysFromNow)));


Learn more in Gary Bernhardt’s original talk about functional core, imperative shell.


By Kyle Freeman

Imagine you're adding a two-player mode to a game. When testing the feature, you launch the game but don't see the option to add a second player. The configuration looks correct; you enabled two-player mode on the last line!

So what happened? Can you spot the bug in the following example?

allow_warping: false

enable_two_players: false

show_end_credits: true

enable_frost_band: false

enable_two_players: true

Using keep-sorted (github.com/google/keep-sorted) to sort lines makes the error easy to spot: the flag enable_two_players is set twice, with different values:

# keep-sorted start

allow_warping: false

enable_frost_band: false

enable_two_players: false

enable_two_players: true

show_end_credits: true

# keep-sorted end

Sorted lists and lines of code are easier to read and maintain, and can help prevent bugs. To use keep-sorted in your source code, config, and text files, install keep-sorted and then follow these instructions: 

  1. Add keep-sorted start and keep-sorted end comments in your file, surrounding the lines you want to sort.

  2. Run keep-sorted: keep-sorted [file1] [file2] ...

  3. (Optional) Add keep-sorted to your pre-commit so it runs automatically on git commit

You can add options to override default behavior. For example, you can ignore case, sort numerically, order by prefixes, and even sort by regular expressions:

bosses := []int{

  // keep-sorted start by_regex=//.*

  111213, // Aethon Annie

  52816,  // Blazing Benny

  711,    // Daisy Dragon

  1003,   // Kenzie Kraken

  // keep-sorted end

}

Remember: before sorting, ensure the original order isn't intentional. For example, order can be critical when loading dependencies.



By Sebastian Dörner

We often read code linearly, from one line to the next. To make code easier to understand and to reduce cognitive load for your readers, make sure that adjacent lines of code are coherent.  One way to achieve this is to order your lines of code to match the data flow inside your method:

fun getSandwich(

    bread: Bread, pasture: Pasture

): Sandwich {

  // This alternates between milk-

// bread-related code.

  val cow = pasture.getCow()

  val slicedBread = bread.slice()

  val milk = cow.getMilk()


  val toast = toastBread(slicedBread)

  val cheese = makeCheese(milk)


  return Sandwich(cheese, toast)

}

fun getSandwich(

    bread: Bread, pasture: Pasture

): Sandwich {

  // Linear flow from cow to milk

// to cheese.

  val cow = pasture.getCow()

  val milk = cow.getMilk()

  val cheese = makeCheese(milk)


  // Linear flow from bread to slicedBread

// to toast.

  val slicedBread = bread.slice()

  val toast = toastBread(slicedBread)


  return Sandwich(cheese, toast)

}

To visually emphasize the grouping of related lines, you can add a blank line between each code block.

Often you can further improve readability by extracting a method, e.g., by extracting the first 3 lines of the function on the above right into a getCheese method. However, in some scenarios, extracting a method isn’t possible or helpful, e.g., if data is used a second time for logging. If you order the lines to match the data flow, you can still increase code clarity:

fun getSandwich(bread: Bread, pasture: Pasture): Sandwich {

  // Both milk and cheese are used below, so this can’t easily be extracted into

// a method.

  val cow = pasture.getCow()

  val milk = cow.getMilk()

  reportFatContentToStreamz(cow.age, milk)

  val cheese = makeCheese(milk)


  val slicedBread = bread.slice()

  val toast = toastBread(slicedBread)


  logWarningIfAnyExpired(bread, toast, milk, cheese)

  return Sandwich(cheese, toast)

}


It isn’t always possible to group variables
perfectly if you have more complicated data flows, but even incremental changes in this direction improve the readability of your code. A good starting point is to declare your variables as close to the first use as possible.
No comments