Boundary Gate¶
Category: Gate Pattern
Overview¶
A boundary gate asserts that one layer does not know about another. A generic library must not import a specific profile; a domain layer must not import the web framework; an application must not reach into a library's internals outside one designated module. The rule is usually stated in a docstring and held only by discipline, which is why it erodes: each individual import looks reasonable in isolation.
Two refinements matter more than the import check itself: exempting the composition point explicitly, and checking the vocabulary as well as the imports.
Concepts¶
Composition Point¶
The one place whose job is to name the concrete implementation. Something has to. An exemption for the composition point is not debt, and keeping it in a different list from the debt exemptions is the point: one shrinks over time, the other does not. Merged, the list becomes noise and stops being maintained.
Vocabulary Leakage¶
A layer can stay free of forbidden imports while its constants, defaults, and docstrings still name the thing it must not know about. The import check passes and the coupling is real, so the gate scans identifiers and string content as well as import statements.
Hidden Dependency¶
The failure the rule prevents. A component that reaches out to find its collaborator — importing another layer to ask whether a context exists, resolving a global, probing for a running server — has a dependency no boundary test can express and no caller can substitute. A helper such as default_profile() that imports the profile package from inside the library is the canonical form.
Usage Guidelines¶
Use when:
- A layering rule exists that only review discipline currently holds
- A library must remain free of any specific consumer's concerns
- An application is permitted to use a library's internals from one module only
Avoid when:
- The dependency direction is already enforced by packaging, so the import cannot resolve
- The layers are not yet distinct enough for the rule to be stated precisely
- Every module would need an exemption, which means the boundary is drawn in the wrong place
Implementation¶
import ast
from collections.abc import Mapping
class BoundaryGate:
"""Fails when a layer imports or names something it must not know about."""
def __init__(
self,
forbidden_prefix: str,
forbidden_vocabulary: frozenset[str],
composition: frozenset[str],
grandfathered: frozenset[str] = frozenset(),
) -> None:
self._forbidden_prefix = forbidden_prefix
self._forbidden_vocabulary = frozenset(
word.lower() for word in forbidden_vocabulary
)
self._composition = frozenset(composition)
self._grandfathered = frozenset(grandfathered)
@property
def composition(self) -> frozenset[str]:
"""Paths exempt on principle. This list does not shrink."""
return self._composition
@property
def grandfathered(self) -> frozenset[str]:
"""Paths exempt as tolerated debt. This list should shrink."""
return self._grandfathered
def _exempt(self, path: str) -> bool:
return path in self._composition or path in self._grandfathered
def import_violations(self, sources: Mapping[str, str]) -> list[str]:
"""Messages for every forbidden import outside an exempt module."""
violations = []
for path, source in sorted(sources.items()):
if self._exempt(path):
continue
for module in _imported_modules(source):
if module == self._forbidden_prefix or module.startswith(
f"{self._forbidden_prefix}."
):
violations.append(
f"{path} imports {module}. The implementation is "
f"supplied by whoever composes the run, never reached for."
)
return violations
def vocabulary_violations(self, sources: Mapping[str, str]) -> list[str]:
"""Messages for forbidden words in identifiers, strings, or docstrings."""
violations = []
for path, source in sorted(sources.items()):
if self._exempt(path):
continue
lowered = source.lower()
violations.extend(
f"{path} names {word!r} outside the composition point. "
f"A layer free of the import can still be coupled by its vocabulary."
for word in sorted(self._forbidden_vocabulary)
if word in lowered
)
return violations
def violations(self, sources: Mapping[str, str]) -> list[str]:
"""Every import and vocabulary violation."""
return self.import_violations(sources) + self.vocabulary_violations(sources)
def _imported_modules(source: str) -> list[str]:
"""Every module named by an import statement in the source."""
modules = []
for node in ast.walk(ast.parse(source)):
if isinstance(node, ast.Import):
modules.extend(alias.name for alias in node.names)
elif isinstance(node, ast.ImportFrom) and node.module:
modules.append(node.module)
return modules
Usage¶
GATE = BoundaryGate(
forbidden_prefix="profiles",
forbidden_vocabulary=frozenset({"miappe"}),
composition=frozenset({"cli/__init__.py"}),
)
assert not GATE.violations(read_package_sources("library"))
Trade-offs¶
Benefits:
- Makes a layering rule enforceable rather than aspirational
- Catches coupling through vocabulary that an import check alone misses
- Distinguishes a principled exemption from unfinished work
Drawbacks:
- Vocabulary matching produces false positives on words with ordinary meanings
- Static import analysis does not see dynamic imports or plugin loading
- Exemption lists invite growth when the boundary is inconvenient
Real-World Examples¶
- Hexagonal or clean architecture checks asserting the domain imports no adapter
- Library tests failing when generic code imports a consumer-specific package
- Monorepo import linters restricting cross-package dependencies
Related Patterns¶
- Grandfathered-Debt Gate handles the debt list this gate keeps separate
- Absence Gate prohibits a specific name rather than a whole layer
- Population Gate analyses source structure with the same technique
API Reference¶
design_patterns.gates.boundary
¶
Boundary Gate: assert that one layer does not know about another.
Two refinements matter more than the import check itself.
The composition point is exempt on principle. Something has to name the concrete implementation, and that place is not debt. Keeping it in a different list from the tolerated violations is the point: one list shrinks over time, the other does not, and merged they become noise that stops being maintained.
The vocabulary is checked as well as the imports. A layer can stay free of forbidden imports while its constants, defaults, and docstrings still name the thing it must not know about.
BoundaryGate
¶
Fails when a layer imports or names something it must not know about.
Example
Source code in src/design_patterns/gates/boundary.py
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 | |
composition
property
¶
Paths exempt on principle. This list does not shrink.
grandfathered
property
¶
Paths exempt as tolerated debt. This list should shrink.
__init__(forbidden_prefix, forbidden_vocabulary, composition, grandfathered=frozenset())
¶
Draw the boundary and record both kinds of exemption.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
forbidden_prefix
|
str
|
Package the checked layer may not import, matched on the module path so submodules are covered too. |
required |
forbidden_vocabulary
|
frozenset[str]
|
Words the checked layer may not use anywhere in its source, matched case-insensitively. |
required |
composition
|
frozenset[str]
|
Paths exempt on principle, where naming the concrete implementation is the module's job. |
required |
grandfathered
|
frozenset[str]
|
Paths exempt as debt. These are not allowed, they are merely not fixed yet, and the list should shrink. |
frozenset()
|
Source code in src/design_patterns/gates/boundary.py
check(sources)
¶
Assert that the layer honours the boundary.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sources
|
Mapping[str, str]
|
Mapping of module path to Python source text. |
required |
Raises:
| Type | Description |
|---|---|
AssertionError
|
If any module crosses the boundary by import or by vocabulary. |
Source code in src/design_patterns/gates/boundary.py
import_violations(sources)
¶
Find forbidden imports outside the exempt modules.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sources
|
Mapping[str, str]
|
Mapping of module path to Python source text. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: One message per forbidden import, ordered by path. |
Source code in src/design_patterns/gates/boundary.py
violations(sources)
¶
Run both halves of the gate.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sources
|
Mapping[str, str]
|
Mapping of module path to Python source text. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: Import violations followed by vocabulary violations. |
Source code in src/design_patterns/gates/boundary.py
vocabulary_violations(sources)
¶
Find forbidden words in identifiers, strings, and docstrings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sources
|
Mapping[str, str]
|
Mapping of module path to Python source text. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
list[str]: One message per forbidden word per file, ordered by path then by word. |