Skip to content

Population Gate

Category: Gate Pattern

Overview

A population gate asserts that only one of a kind exists. It applies where duplication itself is the defect rather than any individual instance being wrong: several hand-written test doubles for the same collaborator, several implementations of the same conversion, several places that parse the same format. The distinguishing feature of the pattern is that detection works on structure rather than on names, because names are chosen by people and people choose differently.

Concepts

Shape Detection

Identification by structure: the set of methods a class defines, the signature it exposes, the calls it makes. A search for class _Fake finds the doubles that happen to be named that way and misses the one called MockClient. A check on the method set finds both.

Sanctioned Instance

The one member of the population that is allowed to exist. Naming it explicitly makes the gate a redirection rather than a prohibition: the failure message can say which implementation to use instead.

Usage Guidelines

Use when:

  • Duplication is the failure mode and the copies drift independently
  • A shared implementation exists and new copies keep appearing beside it
  • The duplicates are recognisable by structure even when named inconsistently

Avoid when:

  • Multiple implementations are legitimate, such as several strategies behind one interface
  • The shape is too common to discriminate, producing matches on unrelated code
  • The population is small and stable enough that review catches additions

Implementation

import ast


class ClassShapeDetector:
    """Finds classes whose method set overlaps a reference set."""

    def __init__(self, methods: set[str], minimum_overlap: int = 2) -> None:
        self._methods = set(methods)
        self._minimum_overlap = minimum_overlap

    def matching_classes(self, source: str) -> list[str]:
        """Names of classes in the source whose methods overlap enough."""
        tree = ast.parse(source)
        matches = []
        for node in ast.walk(tree):
            if not isinstance(node, ast.ClassDef):
                continue
            defined = {
                item.name
                for item in node.body
                if isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef))
            }
            if len(defined & self._methods) >= self._minimum_overlap:
                matches.append(node.name)
        return matches


class PopulationGate:
    """Fails when more than the sanctioned implementation has a given shape."""

    def __init__(
        self,
        detector: ClassShapeDetector,
        sanctioned: set[str],
        replacement: str,
    ) -> None:
        self._detector = detector
        self._sanctioned = set(sanctioned)
        self._replacement = replacement

    def violations(self, sources: dict[str, str]) -> list[str]:
        """Messages for every unsanctioned class, naming its file."""
        return [
            f"{path}:{name} has the shape of the real collaborator; "
            f"use {self._replacement} instead."
            for path, source in sorted(sources.items())
            for name in self._detector.matching_classes(source)
            if name not in self._sanctioned
        ]

Usage

detector = ClassShapeDetector(
    methods={"get", "create", "update", "delete", "list_resources"},
    minimum_overlap=2,
)
gate = PopulationGate(
    detector,
    sanctioned={"FakeClient"},
    replacement="FakeClient from tests/doubles.py",
)

violations = gate.violations({"tests/test_import.py": source_text})
assert not violations, "\n".join(violations)

Trade-offs

Benefits:

  1. Finds instances that a name-based search misses
  2. Names the sanctioned replacement, so the failure is a fix instruction
  3. Resists evasion, because structure is harder to vary than naming

Drawbacks:

  1. Requires tuning: too low an overlap threshold produces false matches, too high misses partial copies
  2. Static analysis sees only what is written literally, missing classes built dynamically
  3. The sanctioned set needs maintenance as the legitimate population changes

Real-World Examples

  • Test suites converging on one shared client double after accumulating hand-written ones
  • Architecture checks asserting a single implementation of a serialisation format
  • Codebase audits finding duplicated retry or backoff logic by call shape

API Reference

design_patterns.gates.population

Population Gate: assert that only one implementation of a kind exists.

The gate applies where duplication itself is the defect rather than any single instance being wrong, most commonly a set of hand-written test doubles for one collaborator. Detection works on structure rather than on names: a search for class _Fake finds the doubles named that way and misses the one called MockClient, while a check on the method set finds both.

ClassShapeDetector

Finds classes whose method set overlaps a reference set.

Example
detector = ClassShapeDetector({"get", "create", "delete"}, minimum_overlap=2)
detector.matching_classes("class MockClient:\n    def get(self): ...")
Source code in src/design_patterns/gates/population.py
class ClassShapeDetector:
    """Finds classes whose method set overlaps a reference set.

    Example:
        ```python
        detector = ClassShapeDetector({"get", "create", "delete"}, minimum_overlap=2)
        detector.matching_classes("class MockClient:\\n    def get(self): ...")
        ```
    """

    def __init__(self, methods: set[str], minimum_overlap: int = 2) -> None:
        """Configure the shape to look for.

        Args:
            methods: Method names characteristic of the real collaborator.
            minimum_overlap: How many of those methods a class must define
                before it counts as the same shape. Too low a value matches
                unrelated classes; too high a value misses partial copies.
        """
        self._methods = set(methods)
        self._minimum_overlap = minimum_overlap

    def matching_classes(self, source: str) -> list[str]:
        """Find classes in a source file that have the configured shape.

        Args:
            source: Python source text to parse.

        Returns:
            list[str]: Names of matching classes, in the order they appear.

        Raises:
            SyntaxError: If the source cannot be parsed.
        """
        matches = []
        for node in ast.walk(ast.parse(source)):
            if not isinstance(node, ast.ClassDef):
                continue
            defined = {
                item.name
                for item in node.body
                if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef)
            }
            if len(defined & self._methods) >= self._minimum_overlap:
                matches.append(node.name)
        return matches

__init__(methods, minimum_overlap=2)

Configure the shape to look for.

Parameters:

Name Type Description Default
methods set[str]

Method names characteristic of the real collaborator.

required
minimum_overlap int

How many of those methods a class must define before it counts as the same shape. Too low a value matches unrelated classes; too high a value misses partial copies.

2
Source code in src/design_patterns/gates/population.py
def __init__(self, methods: set[str], minimum_overlap: int = 2) -> None:
    """Configure the shape to look for.

    Args:
        methods: Method names characteristic of the real collaborator.
        minimum_overlap: How many of those methods a class must define
            before it counts as the same shape. Too low a value matches
            unrelated classes; too high a value misses partial copies.
    """
    self._methods = set(methods)
    self._minimum_overlap = minimum_overlap

matching_classes(source)

Find classes in a source file that have the configured shape.

Parameters:

Name Type Description Default
source str

Python source text to parse.

required

Returns:

Type Description
list[str]

list[str]: Names of matching classes, in the order they appear.

Raises:

Type Description
SyntaxError

If the source cannot be parsed.

Source code in src/design_patterns/gates/population.py
def matching_classes(self, source: str) -> list[str]:
    """Find classes in a source file that have the configured shape.

    Args:
        source: Python source text to parse.

    Returns:
        list[str]: Names of matching classes, in the order they appear.

    Raises:
        SyntaxError: If the source cannot be parsed.
    """
    matches = []
    for node in ast.walk(ast.parse(source)):
        if not isinstance(node, ast.ClassDef):
            continue
        defined = {
            item.name
            for item in node.body
            if isinstance(item, ast.FunctionDef | ast.AsyncFunctionDef)
        }
        if len(defined & self._methods) >= self._minimum_overlap:
            matches.append(node.name)
    return matches

PopulationGate

Fails when more than the sanctioned implementation has a given shape.

Example
gate = PopulationGate(detector, {"FakeClient"}, "tests/doubles.py")
gate.check({"tests/test_import.py": source})
Source code in src/design_patterns/gates/population.py
class PopulationGate:
    """Fails when more than the sanctioned implementation has a given shape.

    Example:
        ```python
        gate = PopulationGate(detector, {"FakeClient"}, "tests/doubles.py")
        gate.check({"tests/test_import.py": source})
        ```
    """

    def __init__(
        self,
        detector: ClassShapeDetector,
        sanctioned: set[str],
        replacement: str,
    ) -> None:
        """Configure the permitted population.

        Args:
            detector: The shape detector identifying candidates.
            sanctioned: Class names allowed to have the shape.
            replacement: What offenders should use instead, named precisely
                enough to act on.
        """
        self._detector = detector
        self._sanctioned = set(sanctioned)
        self._replacement = replacement

    def violations(self, sources: Mapping[str, str]) -> list[str]:
        """Find every unsanctioned class with the configured shape.

        Args:
            sources: Mapping of file path to Python source text.

        Returns:
            list[str]: One message per offender, ordered by file path, naming
                the file, the class, and the sanctioned replacement.
        """
        return [
            f"{path}:{name} has the shape of the real collaborator; "
            f"use {self._replacement} instead."
            for path, source in sorted(sources.items())
            for name in self._detector.matching_classes(source)
            if name not in self._sanctioned
        ]

    def check(self, sources: Mapping[str, str]) -> None:
        """Assert that only the sanctioned implementation has the shape.

        Args:
            sources: Mapping of file path to Python source text.

        Raises:
            AssertionError: If any unsanctioned class matches. The message
                lists every offender rather than the first one.
        """
        violations = self.violations(sources)
        if violations:
            report = "\n".join(violations)
            raise AssertionError(report)

__init__(detector, sanctioned, replacement)

Configure the permitted population.

Parameters:

Name Type Description Default
detector ClassShapeDetector

The shape detector identifying candidates.

required
sanctioned set[str]

Class names allowed to have the shape.

required
replacement str

What offenders should use instead, named precisely enough to act on.

required
Source code in src/design_patterns/gates/population.py
def __init__(
    self,
    detector: ClassShapeDetector,
    sanctioned: set[str],
    replacement: str,
) -> None:
    """Configure the permitted population.

    Args:
        detector: The shape detector identifying candidates.
        sanctioned: Class names allowed to have the shape.
        replacement: What offenders should use instead, named precisely
            enough to act on.
    """
    self._detector = detector
    self._sanctioned = set(sanctioned)
    self._replacement = replacement

check(sources)

Assert that only the sanctioned implementation has the shape.

Parameters:

Name Type Description Default
sources Mapping[str, str]

Mapping of file path to Python source text.

required

Raises:

Type Description
AssertionError

If any unsanctioned class matches. The message lists every offender rather than the first one.

Source code in src/design_patterns/gates/population.py
def check(self, sources: Mapping[str, str]) -> None:
    """Assert that only the sanctioned implementation has the shape.

    Args:
        sources: Mapping of file path to Python source text.

    Raises:
        AssertionError: If any unsanctioned class matches. The message
            lists every offender rather than the first one.
    """
    violations = self.violations(sources)
    if violations:
        report = "\n".join(violations)
        raise AssertionError(report)

violations(sources)

Find every unsanctioned class with the configured shape.

Parameters:

Name Type Description Default
sources Mapping[str, str]

Mapping of file path to Python source text.

required

Returns:

Type Description
list[str]

list[str]: One message per offender, ordered by file path, naming the file, the class, and the sanctioned replacement.

Source code in src/design_patterns/gates/population.py
def violations(self, sources: Mapping[str, str]) -> list[str]:
    """Find every unsanctioned class with the configured shape.

    Args:
        sources: Mapping of file path to Python source text.

    Returns:
        list[str]: One message per offender, ordered by file path, naming
            the file, the class, and the sanctioned replacement.
    """
    return [
        f"{path}:{name} has the shape of the real collaborator; "
        f"use {self._replacement} instead."
        for path, source in sorted(sources.items())
        for name in self._detector.matching_classes(source)
        if name not in self._sanctioned
    ]