Programming Search⌘K

Patternadvanced

Table module

Also called Table Module, table module pattern, module per table.

A table module is one object that holds the business logic for all the rows of one database table, and works on the rows of a record set.

Family
architectural
Intent
A single instance that handles the business logic for all rows in a database table or view.

Intent

A table module is "A single instance that handles the business logic for all rows in a database table or view."1 There is one class for each table, such as orders or customers, and one instance of it works on all the rows. A method gets the id of the row as an argument. Fowler gives it as the third way to organize domain logic, between a Transaction script and a Domain model.2

Problem

"One of the key messages of object orientation is bundling the data with the behavior that uses it."1 A Domain model does this with one object for each row. But a domain model does not fit the relational database well. Fowler: "As a result you often need considerable programmatic gymnastics to pull data in and out of the database, transforming between two different representations of the data."1

Some environments are built around tables. Their tools load the result of a query into a record set, show it in a grid, and write the changes back. A design with an object for each row works against these tools. A Transaction script design fits the tools, but it spreads the rules about one table across many scripts.

Solution

"A Table Module organizes domain logic with one class per table in the data-base, and a single instance of a class contains the various procedures that will act on the data."1 The difference from a domain model is simple: "if you have many orders, a Domain Model will have one order object per order while a Table Module will have one object to handle all orders."1

The parts are:

  • The record set. An in-memory copy of the rows that a query returned, often of several tables. An ADO.NET DataSet is the classic form: "a memory-resident representation of data that provides a consistent relational programming model regardless of the source of the data it contains."3
  • One module for each table. The module gets the record set when it is made. Its methods take the id of a row, and they can also work on all the rows at once.
  • A gateway. Often a Table Data Gateway runs the queries that fill the record set and writes the changes back.
  presentation (a grid of rows)
          |
  OrderModule(record set)      CustomerModule(record set)
    total(order_id)              row(customer_id)
    count_over(limit)            names_with_tier(tier)
          |                            |
  record set: customer, orders, order_line rows
          |
  gateway: select ... from each table

The following program has one table module over the rows of a product table. One instance finds the price of one row and also answers a question about all the rows.

# The record set: the rows of the product table, as a query returns them.
products = [
    {"id": 1, "name": "lamp", "price_cents": 2500, "stock": 4},
    {"id": 2, "name": "desk", "price_cents": 7500, "stock": 0},
]


# One instance of the table module handles all the rows of the table.
class ProductModule:
    def __init__(self, rows):
        self.rows = rows

    def price(self, product_id):
        return next(r["price_cents"] for r in self.rows if r["id"] == product_id)

    def out_of_stock(self):
        return [r["name"] for r in self.rows if r["stock"] == 0]


module = ProductModule(products)
print("price of product 1:", module.price(1))
print("out of stock:", module.out_of_stock())
Output
price of product 1: 2500
out of stock: ['desk']

Example

Each example file loads a record set with the rows of three tables: customers, orders and order lines. A CustomerModule and an OrderModule each take the record set once. OrderModule.total adds the lines of an order and applies the discount of the customer's tier: 10 percent off for a gold customer on 100.00 or more, and 20 percent off for staff. The program prints the totals of the three orders, then two answers about many rows at once, and then the error for an order that is not in the record set. The Python file loads the record set from SQLite; the other files write the rows in the code.

PythonGitHub
import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table customer (id integer primary key, name text, tier text);
create table orders (id integer primary key, customer_id integer);
create table order_line (order_id integer, item text, qty integer, price_cents integer);
insert into customer values (1, 'Ann', 'gold'), (2, 'Bob', 'regular'), (3, 'Cy', 'staff');
insert into orders values (1, 1), (2, 2), (3, 3);
insert into order_line values (1, 'lamp', 2, 2500), (1, 'desk', 1, 7500),
  (2, 'lamp', 1, 2500), (2, 'pen', 3, 500), (3, 'lamp', 1, 2500), (3, 'pen', 3, 500);
""")


class ModuleError(Exception):
    pass


def cents(n):
    return f"{n // 100}.{n % 100:02d}"


# The record set: an in-memory copy of the rows of several tables.
def load_record_set():
    record_set = {}
    for table in ("customer", "orders", "order_line"):
        cursor = db.execute(f"select * from {table}")
        names = [d[0] for d in cursor.description]
        record_set[table] = [dict(zip(names, row)) for row in cursor]
    return record_set


# One table module for each table. One instance handles all the rows of its table.
class CustomerModule:
    def __init__(self, record_set):
        self.rows = record_set["customer"]

    def row(self, customer_id):
        for row in self.rows:
            if row["id"] == customer_id:
                return row
        raise ModuleError(f"no customer {customer_id}")

    def names_with_tier(self, tier):
        return [row["name"] for row in self.rows if row["tier"] == tier]


class OrderModule:
    def __init__(self, record_set, customers):
        self.rows = record_set["orders"]
        self.lines = record_set["order_line"]
        self.customers = customers

    def row(self, order_id):
        for row in self.rows:
            if row["id"] == order_id:
                return row
        raise ModuleError(f"no order {order_id}")

    def subtotal(self, order_id):
        self.row(order_id)
        return sum(l["qty"] * l["price_cents"] for l in self.lines if l["order_id"] == order_id)

    def total(self, order_id):
        subtotal = self.subtotal(order_id)
        tier = self.customers.row(self.row(order_id)["customer_id"])["tier"]
        if tier == "gold" and subtotal >= 10000:
            return subtotal - subtotal // 10
        if tier == "staff":
            return subtotal - subtotal // 5
        return subtotal

    def count_over(self, limit):
        return sum(1 for row in self.rows if self.total(row["id"]) > limit)


record_set = load_record_set()
customers = CustomerModule(record_set)
orders = OrderModule(record_set, customers)
print(f"record set: {len(record_set['customer'])} customers, "
      f"{len(record_set['orders'])} orders, {len(record_set['order_line'])} order lines")
for order_id in (1, 2, 3):
    print(f"order {order_id}: subtotal {cents(orders.subtotal(order_id))}, "
          f"total {cents(orders.total(order_id))}")
print("gold customers:", ", ".join(customers.names_with_tier("gold")))
print("orders over 35.00:", orders.count_over(3500))
try:
    orders.total(9)
except ModuleError as e:
    print("error:", e)
Output
record set: 3 customers, 3 orders, 6 order lines
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
order 3: subtotal 40.00, total 32.00
gold customers: Ann
orders over 35.00: 2
error: no order 9
  • Verdict: idiom. load_record_set copies the rows of three tables into lists of dictionaries, which is the record set. CustomerModule and OrderModule each take the record set once, and their methods take the id of the row to work on.
  • The discount rule is a chain of conditions on the tier in OrderModule.total. A table module has no object for each customer, so it cannot use polymorphism for the tiers.
JavaGitHub
import java.util.List;

public class Main {
    static class ModuleError extends RuntimeException {
        ModuleError(String message) { super(message); }
    }

    static String cents(long n) {
        return String.format("%d.%02d", n / 100, n % 100);
    }

    // The rows of the record set. In JDBC, a ResultSet fills them; in ADO.NET, a DataSet holds them.
    record CustomerRow(int id, String name, String tier) {}
    record OrderRow(int id, int customerId) {}
    record OrderLineRow(int orderId, String item, int qty, long priceCents) {}

    // The record set: an in-memory copy of the rows of several tables.
    record RecordSet(List<CustomerRow> customer, List<OrderRow> orders, List<OrderLineRow> orderLine) {}

    static RecordSet loadRecordSet() {
        return new RecordSet(
                List.of(new CustomerRow(1, "Ann", "gold"), new CustomerRow(2, "Bob", "regular"),
                        new CustomerRow(3, "Cy", "staff")),
                List.of(new OrderRow(1, 1), new OrderRow(2, 2), new OrderRow(3, 3)),
                List.of(new OrderLineRow(1, "lamp", 2, 2500), new OrderLineRow(1, "desk", 1, 7500),
                        new OrderLineRow(2, "lamp", 1, 2500), new OrderLineRow(2, "pen", 3, 500),
                        new OrderLineRow(3, "lamp", 1, 2500), new OrderLineRow(3, "pen", 3, 500)));
    }

    // One table module for each table. One instance handles all the rows of its table.
    static class CustomerModule {
        private final List<CustomerRow> rows;

        CustomerModule(RecordSet recordSet) { rows = recordSet.customer(); }

        CustomerRow row(int customerId) {
            return rows.stream().filter(r -> r.id() == customerId).findFirst()
                    .orElseThrow(() -> new ModuleError("no customer " + customerId));
        }

        List<String> namesWithTier(String tier) {
            return rows.stream().filter(r -> r.tier().equals(tier)).map(CustomerRow::name).toList();
        }
    }

    static class OrderModule {
        private final List<OrderRow> rows;
        private final List<OrderLineRow> lines;
        private final CustomerModule customers;

        OrderModule(RecordSet recordSet, CustomerModule customers) {
            rows = recordSet.orders();
            lines = recordSet.orderLine();
            this.customers = customers;
        }

        OrderRow row(int orderId) {
            return rows.stream().filter(r -> r.id() == orderId).findFirst()
                    .orElseThrow(() -> new ModuleError("no order " + orderId));
        }

        long subtotal(int orderId) {
            row(orderId);
            return lines.stream().filter(l -> l.orderId() == orderId).mapToLong(l -> l.qty() * l.priceCents()).sum();
        }

        long total(int orderId) {
            long subtotal = subtotal(orderId);
            String tier = customers.row(row(orderId).customerId()).tier();
            if (tier.equals("gold") && subtotal >= 10000) return subtotal - subtotal / 10;
            if (tier.equals("staff")) return subtotal - subtotal / 5;
            return subtotal;
        }

        long countOver(long limit) {
            return rows.stream().filter(r -> total(r.id()) > limit).count();
        }
    }

    public static void main(String[] args) {
        RecordSet recordSet = loadRecordSet();
        CustomerModule customers = new CustomerModule(recordSet);
        OrderModule orders = new OrderModule(recordSet, customers);
        System.out.println("record set: " + recordSet.customer().size() + " customers, " + recordSet.orders().size()
                + " orders, " + recordSet.orderLine().size() + " order lines");
        for (int orderId : new int[] {1, 2, 3}) {
            System.out.println("order " + orderId + ": subtotal " + cents(orders.subtotal(orderId)) + ", total "
                    + cents(orders.total(orderId)));
        }
        System.out.println("gold customers: " + String.join(", ", customers.namesWithTier("gold")));
        System.out.println("orders over 35.00: " + orders.countOver(3500));
        try {
            orders.total(9);
        } catch (ModuleError e) {
            System.out.println("error: " + e.getMessage());
        }
    }
}
Output
record set: 3 customers, 3 orders, 6 order lines
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
order 3: subtotal 40.00, total 32.00
gold customers: Ann
orders over 35.00: 2
error: no order 9
  • Verdict: idiom. Records hold the rows, and RecordSet holds the lists. In a Java application, a JDBC ResultSet or a CachedRowSet would give the rows. In C#, an ADO.NET DataSet holds the tables of a record set.
JavaScriptGitHub
class ModuleError extends Error {}

const cents = (n) => `${Math.floor(n / 100)}.${String(n % 100).padStart(2, "0")}`;

// The record set: an in-memory copy of the rows of several tables. Here the rows are written
// in the code; in an application, a query of the database fills the record set.
function loadRecordSet() {
  return {
    customer: [
      { id: 1, name: "Ann", tier: "gold" },
      { id: 2, name: "Bob", tier: "regular" },
      { id: 3, name: "Cy", tier: "staff" },
    ],
    orders: [{ id: 1, customerId: 1 }, { id: 2, customerId: 2 }, { id: 3, customerId: 3 }],
    orderLine: [
      { orderId: 1, item: "lamp", qty: 2, priceCents: 2500 },
      { orderId: 1, item: "desk", qty: 1, priceCents: 7500 },
      { orderId: 2, item: "lamp", qty: 1, priceCents: 2500 },
      { orderId: 2, item: "pen", qty: 3, priceCents: 500 },
      { orderId: 3, item: "lamp", qty: 1, priceCents: 2500 },
      { orderId: 3, item: "pen", qty: 3, priceCents: 500 },
    ],
  };
}

// One table module for each table. One instance handles all the rows of its table.
class CustomerModule {
  constructor(recordSet) { this.rows = recordSet.customer; }

  row(customerId) {
    const row = this.rows.find((r) => r.id === customerId);
    if (!row) throw new ModuleError(`no customer ${customerId}`);
    return row;
  }

  namesWithTier(tier) { return this.rows.filter((r) => r.tier === tier).map((r) => r.name); }
}

class OrderModule {
  constructor(recordSet, customers) {
    this.rows = recordSet.orders;
    this.lines = recordSet.orderLine;
    this.customers = customers;
  }

  row(orderId) {
    const row = this.rows.find((r) => r.id === orderId);
    if (!row) throw new ModuleError(`no order ${orderId}`);
    return row;
  }

  subtotal(orderId) {
    this.row(orderId);
    return this.lines.filter((l) => l.orderId === orderId).reduce((s, l) => s + l.qty * l.priceCents, 0);
  }

  total(orderId) {
    const subtotal = this.subtotal(orderId);
    const tier = this.customers.row(this.row(orderId).customerId).tier;
    if (tier === "gold" && subtotal >= 10000) return subtotal - Math.floor(subtotal / 10);
    if (tier === "staff") return subtotal - Math.floor(subtotal / 5);
    return subtotal;
  }

  countOver(limit) { return this.rows.filter((r) => this.total(r.id) > limit).length; }
}

const recordSet = loadRecordSet();
const customers = new CustomerModule(recordSet);
const orders = new OrderModule(recordSet, customers);
console.log(`record set: ${recordSet.customer.length} customers, ` +
  `${recordSet.orders.length} orders, ${recordSet.orderLine.length} order lines`);
for (const orderId of [1, 2, 3]) {
  console.log(`order ${orderId}: subtotal ${cents(orders.subtotal(orderId))}, total ${cents(orders.total(orderId))}`);
}
console.log("gold customers:", customers.namesWithTier("gold").join(", "));
console.log("orders over 35.00:", orders.countOver(3500));
try {
  orders.total(9);
} catch (e) {
  if (!(e instanceof ModuleError)) throw e;
  console.log("error:", e.message);
}
Output
record set: 3 customers, 3 orders, 6 order lines
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
order 3: subtotal 40.00, total 32.00
gold customers: Ann
orders over 35.00: 2
error: no order 9
  • Verdict: idiom. The record set is a plain object with an array of rows for each table. Each module keeps a reference to the arrays of its table and finds a row with find.
package main

import (
	"errors"
	"fmt"
	"strings"
)

type moduleError struct{ msg string }

func (e *moduleError) Error() string { return e.msg }

func cents(n int) string { return fmt.Sprintf("%d.%02d", n/100, n%100) }

// The rows of the record set. In database/sql, rows.Scan would fill them.
type customerRow struct {
	id         int
	name, tier string
}
type orderRow struct{ id, customerID int }
type orderLineRow struct {
	orderID    int
	item       string
	qty, price int
}

// RecordSet is an in-memory copy of the rows of several tables.
type RecordSet struct {
	customer  []customerRow
	orders    []orderRow
	orderLine []orderLineRow
}

func loadRecordSet() *RecordSet {
	return &RecordSet{
		customer: []customerRow{{1, "Ann", "gold"}, {2, "Bob", "regular"}, {3, "Cy", "staff"}},
		orders:   []orderRow{{1, 1}, {2, 2}, {3, 3}},
		orderLine: []orderLineRow{
			{1, "lamp", 2, 2500}, {1, "desk", 1, 7500},
			{2, "lamp", 1, 2500}, {2, "pen", 3, 500},
			{3, "lamp", 1, 2500}, {3, "pen", 3, 500},
		},
	}
}

// CustomerModule is the table module of the customer table: one value for all its rows.
type CustomerModule struct{ rows []customerRow }

func (m CustomerModule) row(id int) (customerRow, error) {
	for _, r := range m.rows {
		if r.id == id {
			return r, nil
		}
	}
	return customerRow{}, &moduleError{fmt.Sprintf("no customer %d", id)}
}

func (m CustomerModule) NamesWithTier(tier string) []string {
	var names []string
	for _, r := range m.rows {
		if r.tier == tier {
			names = append(names, r.name)
		}
	}
	return names
}

// OrderModule is the table module of the orders table.
type OrderModule struct {
	rows      []orderRow
	lines     []orderLineRow
	customers CustomerModule
}

func (m OrderModule) row(id int) (orderRow, error) {
	for _, r := range m.rows {
		if r.id == id {
			return r, nil
		}
	}
	return orderRow{}, &moduleError{fmt.Sprintf("no order %d", id)}
}

func (m OrderModule) Subtotal(id int) (int, error) {
	if _, err := m.row(id); err != nil {
		return 0, err
	}
	sum := 0
	for _, l := range m.lines {
		if l.orderID == id {
			sum += l.qty * l.price
		}
	}
	return sum, nil
}

func (m OrderModule) Total(id int) (int, error) {
	subtotal, err := m.Subtotal(id)
	if err != nil {
		return 0, err
	}
	o, _ := m.row(id)
	c, err := m.customers.row(o.customerID)
	if err != nil {
		return 0, err
	}
	switch {
	case c.tier == "gold" && subtotal >= 10000:
		return subtotal - subtotal/10, nil
	case c.tier == "staff":
		return subtotal - subtotal/5, nil
	}
	return subtotal, nil
}

func (m OrderModule) CountOver(limit int) int {
	n := 0
	for _, r := range m.rows {
		if t, _ := m.Total(r.id); t > limit {
			n++
		}
	}
	return n
}

func main() {
	rs := loadRecordSet()
	customers := CustomerModule{rs.customer}
	orders := OrderModule{rs.orders, rs.orderLine, customers}
	fmt.Printf("record set: %d customers, %d orders, %d order lines\n", len(rs.customer), len(rs.orders), len(rs.orderLine))
	for _, id := range []int{1, 2, 3} {
		s, _ := orders.Subtotal(id)
		t, _ := orders.Total(id)
		fmt.Printf("order %d: subtotal %s, total %s\n", id, cents(s), cents(t))
	}
	fmt.Println("gold customers:", strings.Join(customers.NamesWithTier("gold"), ", "))
	fmt.Println("orders over 35.00:", orders.CountOver(3500))
	var me *moduleError
	if _, err := orders.Total(9); errors.As(err, &me) {
		fmt.Println("error:", me)
	}
}
Output
record set: 3 customers, 3 orders, 6 order lines
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
order 3: subtotal 40.00, total 32.00
gold customers: Ann
orders over 35.00: 2
error: no order 9
  • Verdict: idiom. Each module is a value type with a slice of the rows of its table, and its methods return an error when the record set has no row with the id. The discount rule is a switch on the tier.
RustGitHub
use std::fmt;

#[derive(Debug)]
struct ModuleError(String);

impl fmt::Display for ModuleError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

fn cents(n: i64) -> String {
    format!("{}.{:02}", n / 100, n % 100)
}

// The rows of the record set.
struct CustomerRow {
    id: u32,
    name: &'static str,
    tier: &'static str,
}
struct OrderRow {
    id: u32,
    customer_id: u32,
}
struct OrderLineRow {
    order_id: u32,
    qty: i64,
    price_cents: i64,
}

// The record set: an in-memory copy of the rows of several tables.
struct RecordSet {
    customer: Vec<CustomerRow>,
    orders: Vec<OrderRow>,
    order_line: Vec<OrderLineRow>,
}

fn load_record_set() -> RecordSet {
    let line = |order_id, qty, price_cents| OrderLineRow { order_id, qty, price_cents };
    RecordSet {
        customer: vec![
            CustomerRow { id: 1, name: "Ann", tier: "gold" },
            CustomerRow { id: 2, name: "Bob", tier: "regular" },
            CustomerRow { id: 3, name: "Cy", tier: "staff" },
        ],
        orders: vec![
            OrderRow { id: 1, customer_id: 1 },
            OrderRow { id: 2, customer_id: 2 },
            OrderRow { id: 3, customer_id: 3 },
        ],
        order_line: vec![
            line(1, 2, 2500), line(1, 1, 7500),
            line(2, 1, 2500), line(2, 3, 500),
            line(3, 1, 2500), line(3, 3, 500),
        ],
    }
}

// One table module for each table. One value handles all the rows of its table.
struct CustomerModule<'a> {
    rows: &'a [CustomerRow],
}

impl<'a> CustomerModule<'a> {
    fn row(&self, id: u32) -> Result<&'a CustomerRow, ModuleError> {
        self.rows.iter().find(|r| r.id == id).ok_or_else(|| ModuleError(format!("no customer {}", id)))
    }

    fn names_with_tier(&self, tier: &str) -> Vec<&'a str> {
        self.rows.iter().filter(|r| r.tier == tier).map(|r| r.name).collect()
    }
}

struct OrderModule<'a> {
    rows: &'a [OrderRow],
    lines: &'a [OrderLineRow],
    customers: &'a CustomerModule<'a>,
}

impl<'a> OrderModule<'a> {
    fn row(&self, id: u32) -> Result<&'a OrderRow, ModuleError> {
        self.rows.iter().find(|r| r.id == id).ok_or_else(|| ModuleError(format!("no order {}", id)))
    }

    fn subtotal(&self, id: u32) -> Result<i64, ModuleError> {
        self.row(id)?;
        Ok(self.lines.iter().filter(|l| l.order_id == id).map(|l| l.qty * l.price_cents).sum())
    }

    fn total(&self, id: u32) -> Result<i64, ModuleError> {
        let subtotal = self.subtotal(id)?;
        let tier = self.customers.row(self.row(id)?.customer_id)?.tier;
        Ok(match tier {
            "gold" if subtotal >= 10000 => subtotal - subtotal / 10,
            "staff" => subtotal - subtotal / 5,
            _ => subtotal,
        })
    }

    fn count_over(&self, limit: i64) -> usize {
        self.rows.iter().filter(|r| self.total(r.id).map_or(false, |t| t > limit)).count()
    }
}

fn main() {
    let rs = load_record_set();
    let customers = CustomerModule { rows: &rs.customer };
    let orders = OrderModule { rows: &rs.orders, lines: &rs.order_line, customers: &customers };
    println!(
        "record set: {} customers, {} orders, {} order lines",
        rs.customer.len(),
        rs.orders.len(),
        rs.order_line.len()
    );
    for id in [1, 2, 3] {
        println!(
            "order {}: subtotal {}, total {}",
            id,
            cents(orders.subtotal(id).unwrap()),
            cents(orders.total(id).unwrap())
        );
    }
    println!("gold customers: {}", customers.names_with_tier("gold").join(", "));
    println!("orders over 35.00: {}", orders.count_over(3500));
    if let Err(e) = orders.total(9) {
        println!("error: {}", e);
    }
}
Output
record set: 3 customers, 3 orders, 6 order lines
order 1: subtotal 125.00, total 112.50
order 2: subtotal 40.00, total 40.00
order 3: subtotal 40.00, total 32.00
gold customers: Ann
orders over 35.00: 2
error: no order 9
  • Verdict: idiom. The modules borrow slices of the record set, so the lifetime 'a ties each module to the record set that it reads. A module cannot outlive its record set, and it cannot change the rows while another module reads them.

Consequences

Benefits.

  • It fits record sets. The logic works on the same rows that the database returns and that the user interface shows. There is no mapping between objects and rows.
  • The rules of a table are in one place. All the logic for orders is in the order module, not spread across scripts.
  • Questions about many rows are easy. A method can work on all the rows of the table, as count_over does. Django gives the same split. Its documentation calls extra manager methods "the preferred way to add" functions for the whole table, and it puts the functions for one row in model methods.4

Liabilities.

The module sees only the record set. The module does not query the database. It works on the rows that it was given. In the following program, the record set holds the lines of one month only. The module finds no lines for an older order and gives a subtotal of 0 with no error.

This code runs but gives a wrong answer on purpose.

import sqlite3

db = sqlite3.connect(":memory:")
db.executescript("""
create table order_line (order_id integer, month text, qty integer, price_cents integer);
insert into order_line values (3, '2026-11', 1, 2500), (4, '2026-10', 2, 500), (4, '2026-10', 1, 900);
""")


class OrderModule:
    def __init__(self, rows):
        self.rows = rows

    def subtotal(self, order_id):
        # Wrong: no check that the record set holds the order.
        return sum(qty * price for oid, qty, price in self.rows if oid == order_id)


# The record set was loaded for one month only.
rows = db.execute("select order_id, qty, price_cents from order_line where month = '2026-11'").fetchall()
module = OrderModule(rows)
print("order 4 in the database:", db.execute("select sum(qty * price_cents) from order_line where order_id = 4").fetchone()[0])
print("order 4 from the module:", module.subtotal(4))
Output
order 4 in the database: 1900
order 4 from the module: 0

Check that the row is in the record set before the calculation, as the row method of the examples does, and load the record set with the rows that each use needs.

No object for each row. There is no customer object, so the rules cannot use polymorphism. Each rule that depends on the tier is a chain of conditions, as in total. As these chains grow, the design has the problem that Replace conditional with polymorphism solves in a Domain model.

No identity. Each call needs the id of the row. A module cannot hold a reference to one order, and two record sets can hold two different copies of one row.

When not to use it

When the logic is complex. Rules with many cases and relations need the objects and the polymorphism of a Domain model.

When the tools do not use record sets. In an environment with a good object-relational mapper and no grids of rows, a table module gives little. A Transaction script is simpler, and a Domain model is more powerful.

Static methods. The module can be a class with static methods that take the record set as an argument. This makes it close to a set of transaction scripts grouped by table.

Instance for a query or a view. A module can work on the rows of a view or a query, not only a table. The pattern definition says "a database table or view".1

Related patterns. A Table Data Gateway is the data source pattern that matches a table module: one object for each table that runs the SQL. A Row Data Gateway or an Active Record has one object for each row instead. The Record set is the data structure that the module works on.

Known uses

  • .NET applications built on ADO.NET, where a DataSet holds "the tables that contain, order, and constrain the data, as well as the relationships between the tables",3 and a DataAdapter fills it and writes the changes back.3
  • Django managers. "A Manager is the interface through which database query operations are provided to Django models."4 Extra manager methods hold the logic for the whole table, while model methods hold the logic for one row.4

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Table Module, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 9, Domain Logic Patterns, Table Module
  3. Microsoft, ADO.NET, DataSets, DataTables, and DataViews, introduction
  4. Django 5.2 documentation, Managers, introduction; Adding extra manager methods

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/B853HS/text.yaml