Part II — Intermediate Development · Chapter 7 · Lesson 4 of 7 · 8 min read
Lesson 4: Structural Protocols and Project-Wide Contracts
Lesson level: Intermediate
Purpose: Define reusable behavior contracts that types satisfy through their available structure, then apply those contracts consistently across modules and project boundaries.
Learning objectives
By the end of this lesson, you should be able to:
- explain structural protocol matching;
- distinguish protocols from nominal identity and concrete types;
- define the minimum members required by an operation;
- check member names, parameters, and return contracts;
- use protocols as generic constraints;
- design stable contracts across modules;
- analyze compatibility when protocols evolve;
- diagnose missing or incompatible members; and
- separate static conformance from runtime boundary validation.
4.1 Behavior instead of identity
A concrete type names one particular representation. A structural protocol describes the behavior a value must provide. A type satisfies the protocol when its available members match the required structure; it does not need to inherit from, register with, or explicitly name the protocol.
Consider a conceptual protocol for values that can produce a stable label:
protocol Labelled { function label() -> String }
Any type with a compatible zero-argument label method returning a string can satisfy this contract. The consumer depends on behavior rather than the implementation’s name or storage.
4.2 Structural and nominal thinking
Nominal compatibility asks whether a type has a declared identity or relationship. Structural compatibility asks whether the required members exist with compatible signatures. Structural protocols are valuable when independent modules should cooperate without sharing an inheritance hierarchy.
Structural matching is not “anything with a similar name.” Parameter count, parameter types, return type, and relevant member kind must match the protocol’s contract.
4.3 Protocols are consumer contracts
Design a protocol from what the consuming algorithm needs, not from every member an implementation happens to expose. A reporting function that only needs label() and to_record() should not require persistence, logging, or unrelated domain operations.
Interface-segregation rule. Small, focused protocols are easier to satisfy, test, evolve, and reuse than broad “god interfaces.”
4.4 Member-signature matching
Conformance requires more than the presence of a member name. For each required operation, check:
- the member name;
- whether it is callable or value-like as required;
- the number and order of parameters;
- parameter compatibility;
- the return contract;
- generic parameters and constraints, where relevant; and
- asynchronous behavior when the contract distinguishes it.
A type with label(prefix: String) -> String does not satisfy a requirement for label() -> String. Likewise, returning an integer does not satisfy a string result merely because both can be printed.
4.5 Extra members are allowed
A protocol specifies the minimum required structure. Implementations may provide additional members without losing conformance. Consumers typed against the protocol should rely only on the declared contract, which keeps them decoupled from implementation-specific features.
Do not “reach through” a protocol-typed value to use an extra member unless the consumer deliberately requires a stronger protocol or concrete type.
4.6 Protocols as generic constraints
Generics preserve type relationships; protocols define what operations a generic algorithm may use.
function labels<T: Labelled>(items: List<T>) -> List<String> { let output = [] for item in items { output.append(item.label()) } return output }
The constraint justifies calling label() on each T. Without it, the generic body cannot assume that operation exists.
4.7 Multiple protocol requirements
An algorithm may require several independent behaviors. Keep those behaviors separate when they are useful independently, then combine constraints at the use site.
For example, a sorted report may require both stable labelling and comparison. A type must satisfy every required contract. Avoid merging unrelated behaviors into one protocol merely because one current function needs both.
4.8 Properties and callable members
A value property and a zero-argument method are not automatically interchangeable. If a protocol requires status: String, an implementation offering only status() -> String has a different structure.
Choose the member form deliberately. Use a value-like member for stable observable state and a method for behavior, computation, or an operation with meaningful execution semantics.
4.9 Static conformance versus runtime validity
A type may structurally satisfy a protocol while an individual runtime value remains invalid. A record exporter can expose to_record() -> Map yet still return a map missing required business fields.
Protocols establish available operations and their types. Runtime validation still checks external values, ranges, invariants, permissions, resource limits, and portable boundary shapes.
4.10 Adapters for external and legacy values
When a host object or legacy value almost satisfies a protocol, prefer a narrow adapter over weakening the protocol or exposing the object directly. The adapter validates the original value, presents the required members, and converts outputs to approved portable forms.
This preserves least privilege and creates one reviewable location for compatibility logic.
4.11 Protocols across module boundaries
A shared protocol can stabilize collaboration between producer and consumer modules. The contract module defines behavior; implementation modules supply conforming types; consumer modules depend on the protocol rather than importing every implementation.
A healthy dependency direction is:
- place the focused protocol in a stable shared module;
- keep implementation details in producer modules;
- type consumer parameters with the protocol;
- validate untrusted data before constructing adapters or implementations; and
- test conformance and behavior independently.
Avoid circular dependencies in which the shared contract imports concrete implementations that already depend on it.
4.12 Project-wide contract inventory
Maintain a small inventory for important protocols:
| Field | Purpose |
|---|---|
| Name and owner | Identifies stewardship and review responsibility. |
| Required members | Defines exact structural obligations. |
| Known implementations | Shows current producers without limiting future ones. |
| Consumers | Reveals change impact. |
| Version and stability | Communicates compatibility expectations. |
| Runtime invariants | Records requirements types cannot prove. |
This inventory supports project-wide checks and deliberate evolution without turning protocols into implementation registries.
4.13 Evolving a protocol safely
Adding a required member is a breaking change for every existing implementation that lacks it. Changing a parameter or return type can break both implementations and consumers. Removing a member can break consumers even if implementations remain valid.
Use this evolution sequence:
- identify every consumer and known implementation;
- define the compatibility goal;
- add a new protocol or transitional adapter when necessary;
- update implementations in small verified batches;
- run project-wide semantic checks and tests;
- migrate consumers;
- deprecate the old contract with a clear timeline; and
- remove compatibility code only after usage evidence permits it.
4.14 Protocol versioning patterns
- Additive new protocol: define a stronger successor while preserving the old contract.
- Composed capability: keep the base protocol and add an independent behavior protocol.
- Adapter period: wrap legacy implementations during migration.
- Consumer narrowing: reduce an overly broad requirement to the members actually used.
- Explicit breaking release: change the contract with coordinated migration and release evidence.
Avoid silently changing a shared protocol and relying on scattered compile failures as the migration plan.
4.15 Conformance diagnostics
Useful diagnostics identify the required protocol, candidate type, missing or incompatible member, expected signature, and actual signature. Common causes include:
- missing member;
- misspelled member name;
- property-versus-method mismatch;
- wrong parameter count or order;
- incompatible parameter or return type;
- unsatisfied nested generic constraint;
- incorrect asynchronous contract; and
- uncertain type information at a gradual boundary.
Repair the narrowest root cause. Do not add dummy members, broad return types, or unsafe conversions solely to satisfy the checker.
4.16 Diagnostic workflow
- Read the required protocol and exact failing member.
- Inspect the candidate member’s complete signature.
- Compare member kind, parameters, result, and generic constraints.
- Decide whether the implementation, adapter, or protocol is wrong.
- Make the smallest contract-preserving change.
- Run project-wide semantic checks.
- Run behavior and boundary tests.
- Review other consumers before publishing the change.
4.17 Worked architecture example
A project has CSV, JSON, database, and HTTP data sources. Instead of one service importing each provider type, define a focused source protocol conceptually requiring name() -> String, health() -> Map, and fetch(query: Map) -> Result<List<Map>, Error>.
Each provider can use different credentials, transports, and retry logic while the ingestion workflow depends on one contract. Runtime policies still control permissions, deadlines, pagination, record validation, and portable results.
4.18 Common mistakes
- Requiring implementation identity. Structural protocols depend on compatible members, not a shared class name.
- Designing from one implementation. Define what consumers need.
- Creating an oversized protocol. Split independent behaviors.
- Matching names only. Verify complete signatures.
- Confusing a property with a method. Member kind is part of the contract.
- Using unconstrained generics as though members exist. Add a focused protocol constraint.
- Assuming conformance validates data. Keep runtime checks.
- Changing a shared protocol silently. Inventory impact and migrate deliberately.
- Exposing powerful host objects. Use narrow adapters and portable values.
- Adding dummy members to pass checks. Correct the design or implementation.
4.19 Guided practice
- List the members a simple Labelled protocol should require.
- Decide whether a value property satisfies a method requirement.
- Compare two method signatures and identify the incompatibility.
- Reduce an oversized protocol to the members one consumer actually uses.
- Constrain a generic function that needs a label operation.
- Design separate protocols for health reporting and record fetching.
- Describe the adapter needed for a legacy provider.
- Classify adding a required member as compatible or breaking.
4.20 Hands-on lab: Build a project-wide rules-provider contract
Scenario. A rules service loads policy decisions from local, embedded, and remote providers without coupling its core workflow to provider implementations.
Requirements
- Define a focused provider protocol with name, health, and evaluate operations.
- Specify exact parameter and return contracts using portable values.
- Create conceptual local, embedded, and remote implementations.
- Use the protocol as a constraint in one generic batch evaluator.
- Keep credentials, transport objects, and host handles outside the protocol.
- Add adapters for one legacy provider and one host-specific object.
- Validate input and output maps at runtime.
- Introduce missing-member, wrong-parameter, wrong-return, and property/method mismatches.
- Record diagnostics and minimal corrections.
- Propose a version-two capability without silently breaking version one.
- Run project-wide semantic checks and provider behavior tests.
Acceptance criteria. All intended providers conform; invalid candidates fail with specific diagnostics; the workflow imports only the shared contract; boundary values remain portable; runtime validation remains active; and the evolution plan identifies consumers, implementations, adapters, and deprecation steps.
4.21 Review questions
- What makes a protocol structural?
- How does structural compatibility differ from nominal identity?
- Why should a protocol reflect consumer needs?
- Which parts of a member signature affect conformance?
- Why may an implementation expose extra members?
- How do protocols make generic operations safe?
- Why should independent behaviors use separate protocols?
- Why does static conformance not replace runtime validation?
- Why is adding a required member usually breaking?
- What evidence is needed before retiring an old project-wide contract?
4.22 Applied challenge
Review two earlier course projects and identify duplicated behavioral assumptions across modules. Define the smallest structural protocols that capture those assumptions, map known implementations and consumers, add one generic constrained utility, and write a safe evolution plan for a future requirement.
Lesson summary
Structural protocols define reusable behavior by required members rather than implementation identity. Sound conformance checks complete signatures, generic constraints justify operations, adapters contain legacy or host-specific values, and focused shared protocols reduce module coupling. Project-wide contracts require ownership, inventories, compatibility analysis, semantic checks, runtime validation, tests, and deliberate evolution.
Lesson status: Ready for review.
Next: Chapter 7, Lesson 5 — Option, Result, and Future Types.