HTTP and the database don't belong in the same file

April 15, 2024

Key takeaway: When one file requires both an HTTP library and a database driver, move one of those jobs into its own file.

If a file imports both an HTTP library and a database driver, it’s doing at least two jobs. Reading the imports first is about the cheapest architecture review you can do.

Here’s a typical Sinatra endpoint:

require "sinatra"
require "json"
require "pg"

post "/orders" do
  payload = JSON.parse(request.body.read)
  halt 422 if payload["items"].empty?

  total = payload["items"].sum { |item| item["price"] * item["quantity"] }

  db = PG.connect(ENV.fetch("DATABASE_URL"))
  db.exec_params(
    "INSERT INTO orders (customer_id, total) VALUES ($1, $2)",
    [payload["customer_id"], total]
  )

  status 201
  { total: total }.to_json
end

The business rule, that an order needs items and its total is price times quantity, is trapped between parsing a request and writing a row. A nightly CSV import has to duplicate it or fake a request to reach it. And testing one line of arithmetic means booting the app and pointing it at a real Postgres. Tests like that are slow, so people write fewer of them.

Split it along the imports. The rule goes in a module with no requires:

# order_total.rb: no requires at all
module OrderTotal
  def self.call(items)
    raise ArgumentError, "an order needs at least one item" if items.empty?

    items.sum { |item| item.fetch(:price) * item.fetch(:quantity) }
  end
end

The SQL goes in a repository that requires pg and knows nothing about HTTP. The route parses the request, calls the other two, and formats the response. Now the rule’s test is one line, assert_equal 1000, OrderTotal.call([{ price: 500, quantity: 2 }]), and a database move only touches the repository.

This is Alistair Cockburn’s ports and adapters, the same shape as Gary Bernhardt’s “functional core, imperative shell.”

A fifty-line script that pulls JSON and inserts rows can stay in one file. This is for code that’s going to grow.