PeaBox Lab › PeaLang › Learn › Chapter 7 › Lesson 4

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:

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:

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:

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:

FieldPurpose
Name and ownerIdentifies stewardship and review responsibility.
Required membersDefines exact structural obligations.
Known implementationsShows current producers without limiting future ones.
ConsumersReveals change impact.
Version and stabilityCommunicates compatibility expectations.
Runtime invariantsRecords 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:

4.14 Protocol versioning patterns

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:

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

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

4.19 Guided practice

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

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

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.

← Previous Next →