Programming Search⌘K

Patterncore

Layer supertype

Also called Layer Supertype, base class of a layer, domain object base class.

A layer supertype is one base type for all the types of a layer, such as all the domain objects, so that their shared behaviour, like the identity and the equality, is written once.

Family
architectural
Intent
Give all the types of a layer one supertype that holds the behaviour they share.

Intent

A layer supertype is "A type that acts as the supertype for all types in its layer."1 The behaviour that all the types of the layer share is written once, in the supertype.

Problem

The types of one layer often need the same code. All the domain objects have an ID and compare by it. All the controllers check the user. All the data mappers open a connection in the same way. The catalog says: "It's not uncommon for all the objects in a layer to have methods you don't want to have duplicated throughout the system."1

If each class writes this code again, the copies drift apart. One class forgets a method, another class does it in a slightly different way, and a fix must be made in each copy.

Solution

"You can move all of this behavior into a common Layer Supertype."1 The parts are:

  • The supertype. One abstract base class, or in languages without inheritance, a trait or an embedded struct, for one layer. It holds the shared fields and methods.
  • The types of the layer. Each one extends the supertype and adds only what is its own.
  • Hooks. Where the shared code needs a part that differs for each type, the supertype calls a method that each subclass overrides, as in the Template Method pattern.

A common use is a supertype for the domain objects that holds the Identity Field.2 It can also define the equality by ID. Each layer has its own supertype, so the domain objects and the data mappers do not share one.

                 DomainObject           id, equality by kind and id, check() calls rules()
                 /          \
          Customer          Product     each gives only its own fields and rules()

In the following program, the supertype defines the equality and the hash once. Two objects for the same row are equal, and objects of two types with the same ID are not.

class DomainObject:  # the layer supertype
    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        return type(self) is type(other) and self.id == other.id

    def __hash__(self):
        return hash((type(self), self.id))


class Customer(DomainObject):
    pass


class Invoice(DomainObject):
    pass


print("same customer row, two objects:", Customer(1) == Customer(1))
print("in one set:", len({Customer(1), Customer(1), Invoice(1)}))
Output
same customer row, two objects: True
in one set: 2

Example

Each example file has a supertype for the domain objects, with an ID, the equality by the type and the ID, and a check method that collects the broken rules. Customer and Product give only their fields and their rules. The program checks a valid customer, a valid product and a product with an empty name and a negative price. Then it compares two objects for the same customer row, which are equal, and a customer and a product with the same ID, which are not. In Go and Rust, which have no inheritance, the supertype is an embedded struct with functions on an interface, and a trait with default methods.

PythonGitHub
class DomainObject:
    """The layer supertype: every domain object has an ID, equality by ID and a check."""

    def __init__(self, id):
        self.id = id

    def __eq__(self, other):
        return type(self) is type(other) and self.id == other.id

    def __hash__(self):
        return hash((type(self).__name__, self.id))

    def rules(self):  # each subclass gives its own rules
        return []

    def check(self):
        problems = [message for ok, message in self.rules() if not ok]
        return "valid" if not problems else "invalid: " + ", ".join(problems)


class Customer(DomainObject):
    def __init__(self, id, name):
        super().__init__(id)
        self.name = name

    def rules(self):
        return [(self.name != "", "name is empty")]


class Product(DomainObject):
    def __init__(self, id, name, price_cents):
        super().__init__(id)
        self.name, self.price_cents = name, price_cents

    def rules(self):
        return [(self.name != "", "name is empty"), (self.price_cents >= 0, "price is negative")]


for o in [Customer(1, "ann"), Product(2, "pen", 150), Product(3, "", -5)]:
    print(f"{type(o).__name__.lower()} {o.id} {o.name or '(no name)'}: {o.check()}")
yes_no = {True: "yes", False: "no"}
print("customer 1 equals customer 1 loaded again:", yes_no[Customer(1, "ann") == Customer(1, "ann")])
print("customer 1 equals product 1:", yes_no[Customer(1, "ann") == Product(1, "ann", 0)])
Output
customer 1 ann: valid
product 2 pen: valid
product 3 (no name): invalid: name is empty, price is negative
customer 1 equals customer 1 loaded again: yes
customer 1 equals product 1: no
  • Verdict: native. DomainObject is a normal base class. It defines __eq__ and __hash__ once, so two objects for the same row are equal and fit in one set. check calls rules, which each subclass overrides.
  • type(self) is type(other) keeps a customer and a product with the same ID apart.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class Main {
    record Rule(boolean ok, String message) {}

    // The layer supertype: every domain object has an ID, equality by ID and a check.
    abstract static class DomainObject {
        final long id;
        DomainObject(long id) { this.id = id; }

        abstract String name();
        abstract List<Rule> rules(); // each subclass gives its own rules

        String check() {
            List<String> problems = new ArrayList<>();
            for (Rule r : rules()) if (!r.ok()) problems.add(r.message());
            return problems.isEmpty() ? "valid" : "invalid: " + String.join(", ", problems);
        }

        @Override public boolean equals(Object other) {
            return other != null && other.getClass() == getClass() && ((DomainObject) other).id == id;
        }

        @Override public int hashCode() { return Objects.hash(getClass().getName(), id); }
    }

    static class Customer extends DomainObject {
        final String name;
        Customer(long id, String name) { super(id); this.name = name; }
        String name() { return name; }
        List<Rule> rules() { return List.of(new Rule(!name.isEmpty(), "name is empty")); }
    }

    static class Product extends DomainObject {
        final String name;
        final long priceCents;
        Product(long id, String name, long priceCents) { super(id); this.name = name; this.priceCents = priceCents; }
        String name() { return name; }
        List<Rule> rules() {
            return List.of(new Rule(!name.isEmpty(), "name is empty"), new Rule(priceCents >= 0, "price is negative"));
        }
    }

    static String yesNo(boolean b) { return b ? "yes" : "no"; }

    public static void main(String[] args) {
        for (DomainObject o : List.of(new Customer(1, "ann"), new Product(2, "pen", 150), new Product(3, "", -5))) {
            String name = o.name().isEmpty() ? "(no name)" : o.name();
            System.out.println(o.getClass().getSimpleName().toLowerCase() + " " + o.id + " " + name + ": " + o.check());
        }
        System.out.println("customer 1 equals customer 1 loaded again: " + yesNo(new Customer(1, "ann").equals(new Customer(1, "ann"))));
        System.out.println("customer 1 equals product 1: " + yesNo(new Customer(1, "ann").equals(new Product(1, "ann", 0))));
    }
}
Output
customer 1 ann: valid
product 2 pen: valid
product 3 (no name): invalid: name is empty, price is negative
customer 1 equals customer 1 loaded again: yes
customer 1 equals product 1: no
  • Verdict: native. DomainObject is an abstract class. It overrides equals and hashCode for all the domain classes, and check uses the abstract method rules. getClass() == keeps a customer and a product with the same ID apart.
JavaScriptGitHub
// The layer supertype: every domain object has an ID, equality by ID and a check.
class DomainObject {
  constructor(id) {
    this.id = id;
  }

  equals(other) {
    return other !== null && other.constructor === this.constructor && other.id === this.id;
  }

  rules() {
    return []; // each subclass gives its own rules
  }

  check() {
    const problems = this.rules().filter(([ok]) => !ok).map(([, message]) => message);
    return problems.length === 0 ? "valid" : "invalid: " + problems.join(", ");
  }
}

class Customer extends DomainObject {
  constructor(id, name) {
    super(id);
    this.name = name;
  }

  rules() {
    return [[this.name !== "", "name is empty"]];
  }
}

class Product extends DomainObject {
  constructor(id, name, priceCents) {
    super(id);
    this.name = name;
    this.priceCents = priceCents;
  }

  rules() {
    return [
      [this.name !== "", "name is empty"],
      [this.priceCents >= 0, "price is negative"],
    ];
  }
}

for (const o of [new Customer(1, "ann"), new Product(2, "pen", 150), new Product(3, "", -5)]) {
  console.log(`${o.constructor.name.toLowerCase()} ${o.id} ${o.name || "(no name)"}: ${o.check()}`);
}
const yesNo = (b) => (b ? "yes" : "no");
console.log("customer 1 equals customer 1 loaded again:", yesNo(new Customer(1, "ann").equals(new Customer(1, "ann"))));
console.log("customer 1 equals product 1:", yesNo(new Customer(1, "ann").equals(new Product(1, "ann", 0))));
Output
customer 1 ann: valid
product 2 pen: valid
product 3 (no name): invalid: name is empty, price is negative
customer 1 equals customer 1 loaded again: yes
customer 1 equals product 1: no
  • Verdict: native. DomainObject is a base class with extends. JavaScript has no operator overloading, so equality is the method equals, and === still compares the identity of two objects.
  • other.constructor === this.constructor keeps a customer and a product with the same ID apart.
package main

import (
	"fmt"
	"strings"
)

// Go has no inheritance. The layer supertype is a struct that each domain type
// embeds, and a function that works on an interface of all domain objects.

type rule struct {
	ok      bool
	message string
}

// DomainObject is embedded in every domain type of the layer.
type DomainObject struct {
	Kind string
	ID   int
}

// Key is the identity of a domain object: its kind and its ID.
func (d DomainObject) Key() DomainObject { return d }

// Entity is what every domain type has, through the embedded DomainObject
// and its own Name and Rules methods.
type Entity interface {
	Key() DomainObject
	Name() string
	Rules() []rule
}

// Check is the shared behaviour of the layer.
func Check(e Entity) string {
	var problems []string
	for _, r := range e.Rules() {
		if !r.ok {
			problems = append(problems, r.message)
		}
	}
	if len(problems) == 0 {
		return "valid"
	}
	return "invalid: " + strings.Join(problems, ", ")
}

// Same compares two domain objects by kind and ID.
func Same(a, b Entity) bool { return a.Key() == b.Key() }

type Customer struct {
	DomainObject
	name string
}

func NewCustomer(id int, name string) Customer { return Customer{DomainObject{"customer", id}, name} }
func (c Customer) Name() string                { return c.name }
func (c Customer) Rules() []rule               { return []rule{{c.name != "", "name is empty"}} }

type Product struct {
	DomainObject
	name       string
	priceCents int
}

func NewProduct(id int, name string, price int) Product {
	return Product{DomainObject{"product", id}, name, price}
}
func (p Product) Name() string { return p.name }
func (p Product) Rules() []rule {
	return []rule{{p.name != "", "name is empty"}, {p.priceCents >= 0, "price is negative"}}
}

func yesNo(b bool) string {
	if b {
		return "yes"
	}
	return "no"
}

func main() {
	for _, e := range []Entity{NewCustomer(1, "ann"), NewProduct(2, "pen", 150), NewProduct(3, "", -5)} {
		name := e.Name()
		if name == "" {
			name = "(no name)"
		}
		fmt.Printf("%s %d %s: %s\n", e.Key().Kind, e.Key().ID, name, Check(e))
	}
	fmt.Println("customer 1 equals customer 1 loaded again:", yesNo(Same(NewCustomer(1, "ann"), NewCustomer(1, "ann"))))
	fmt.Println("customer 1 equals product 1:", yesNo(Same(NewCustomer(1, "ann"), NewProduct(1, "ann", 0))))
}
Output
customer 1 ann: valid
product 2 pen: valid
product 3 (no name): invalid: name is empty, price is negative
customer 1 equals customer 1 loaded again: yes
customer 1 equals product 1: no
  • Verdict: idiom. Go has no inheritance. Each domain type embeds the DomainObject struct, so it gets the fields Kind and ID and the method Key. The shared behaviour is the functions Check and Same, which take the Entity interface.
  • An embedded struct cannot call a method of the type that embeds it, so the shared code is a function on the interface, not a method of DomainObject.
RustGitHub
// Rust has no inheritance. The layer supertype is a trait with default methods,
// which every domain type of the layer implements.
trait DomainObject {
    const KIND: &'static str;
    fn id(&self) -> u32;
    fn name(&self) -> &str;
    fn rules(&self) -> Vec<(bool, &'static str)>; // each type gives its own rules

    fn check(&self) -> String {
        let problems: Vec<&str> = self.rules().into_iter().filter(|(ok, _)| !ok).map(|(_, m)| m).collect();
        if problems.is_empty() { "valid".to_string() } else { format!("invalid: {}", problems.join(", ")) }
    }

    fn same<O: DomainObject>(&self, other: &O) -> bool {
        Self::KIND == O::KIND && self.id() == other.id()
    }

    fn describe(&self) -> String {
        let name = if self.name().is_empty() { "(no name)" } else { self.name() };
        format!("{} {} {}: {}", Self::KIND, self.id(), name, self.check())
    }
}

struct Customer {
    id: u32,
    name: String,
}

impl DomainObject for Customer {
    const KIND: &'static str = "customer";
    fn id(&self) -> u32 { self.id }
    fn name(&self) -> &str { &self.name }
    fn rules(&self) -> Vec<(bool, &'static str)> { vec![(!self.name.is_empty(), "name is empty")] }
}

struct Product {
    id: u32,
    name: String,
    price_cents: i64,
}

impl DomainObject for Product {
    const KIND: &'static str = "product";
    fn id(&self) -> u32 { self.id }
    fn name(&self) -> &str { &self.name }
    fn rules(&self) -> Vec<(bool, &'static str)> {
        vec![(!self.name.is_empty(), "name is empty"), (self.price_cents >= 0, "price is negative")]
    }
}

fn customer(id: u32, name: &str) -> Customer { Customer { id, name: name.to_string() } }
fn product(id: u32, name: &str, price_cents: i64) -> Product { Product { id, name: name.to_string(), price_cents } }
fn yes_no(b: bool) -> &'static str { if b { "yes" } else { "no" } }

fn main() {
    println!("{}", customer(1, "ann").describe());
    println!("{}", product(2, "pen", 150).describe());
    println!("{}", product(3, "", -5).describe());
    println!("customer 1 equals customer 1 loaded again: {}", yes_no(customer(1, "ann").same(&customer(1, "ann"))));
    println!("customer 1 equals product 1: {}", yes_no(customer(1, "ann").same(&product(1, "ann", 0))));
}
Output
customer 1 ann: valid
product 2 pen: valid
product 3 (no name): invalid: name is empty, price is negative
customer 1 equals customer 1 loaded again: yes
customer 1 equals product 1: no
  • Verdict: idiom. Rust has no inheritance. The layer supertype is the trait DomainObject, with the associated constant KIND, required methods for the data of each type, and default methods check, same and describe for the shared behaviour.
  • A trait cannot hold fields, so each type keeps its own id field and returns it from id.

Consequences

Benefits.

  • No duplicated code. The shared behaviour is in one place, so a fix or a change is made once.
  • A uniform layer. All the types of the layer behave in the same way, and code that works on the layer can use the supertype.
  • A place for the rules of the layer. New behaviour for all the domain objects, such as a change log, goes into the supertype.

Liabilities.

Without a supertype, a class forgets the shared code. In the following program, each class writes its own equality, and Invoice forgot it. Two objects for the same invoice row are not equal.

This code runs but gives a wrong answer on purpose.

class Customer:
    def __init__(self, id):
        self.id = id

    def __eq__(self, other):  # each class writes its own equality
        return isinstance(other, Customer) and self.id == other.id

    def __hash__(self):
        return hash(self.id)


class Invoice:  # this class forgot it
    def __init__(self, id):
        self.id = id


print("same customer row loaded twice is equal:", Customer(1) == Customer(1))
print("same invoice row loaded twice is equal:", Invoice(1) == Invoice(1))
Output
same customer row loaded twice is equal: True
same invoice row loaded twice is equal: False

Move the equality into one supertype, and let Customer and Invoice extend it.

A base class that grows too much. It is easy to put into the supertype code that only some of the types need. Keep only the behaviour that all the types of the layer share.

One base class only. In a language with single inheritance, the types of the layer cannot extend another class. A framework base class can take that place, and then the supertype must extend it.

When not to use it

When the types share only a little code. A helper function, or a small mixin, is simpler than a base class for all the types.

When composition fits better. If the shared code is a service, such as logging or access to the database, give the objects that service and do not make it a base class.

Framework base classes. Many frameworks give the application a supertype for one layer. In Rails, "ApplicationRecord is the base class for all Active Record models in your app."3 It inherits from ActiveRecord::Base, so each model of the application gets the behaviour of Active Record.

Abstract models. In Django, "Abstract base classes are useful when you want to put some common information into a number of other models."4 An abstract model gives its fields to each subclass and has no table of its own.

Related patterns. The supertype often uses the Template Method pattern for its hooks. In a Domain model, the supertype of the domain objects holds the Identity Field.

Known uses

  • Rails applications have an ApplicationRecord class that all their models extend.3
  • Django models extend django.db.models.Model, and abstract models add a supertype of the application.4

References

  1. Martin Fowler, Catalog of Patterns of Enterprise Application Architecture, Layer Supertype, pattern summary
  2. Martin Fowler, Patterns of Enterprise Application Architecture, Addison-Wesley, 2002, Chapter 18, Base Patterns, Layer Supertype
  3. Rails Guides, Active Record Basics, Creating Active Record Models
  4. Django 5.2 documentation, Models, Abstract base classes

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/B6CMAT/text.yaml