liveBook · Manning

Contract

As explained in Unit Testing Principles, Practices, and Patterns

The public API is the set of publicly accessible operations and contracts through which a software component can be used.

An API is the set of publicly accessible operations and state through which a component helps clients achieve their goals. A well-designed API makes this public surface coincide with observable behavior while hiding implementation details behind a private API. section 5.2 section 5.5

Classify an API along two independent dimensions:

  • Public versus private: access modifiers determine what client code can reach. section 5.2
  • Observable behavior versus implementation details: observable code exposes an operation or state that helps a client achieve a goal; other code is internal. section 5.2
  • Avoid public implementation details. When the public API extends beyond observable behavior, clients can depend on internals and potentially bypass invariants. section 5.5

Refactor the surface, not the test

A User class exposes NormalizeName publicly, even though clients only need to assign a valid Name. That leaks an implementation detail and forces callers to perform normalization themselves. Move normalization into the Name setter and make NormalizeName private; callers then write user.Name = newName. Similarly, a purchase should be one public operation that both acquires the product and reduces inventory, rather than requiring a second client call. section 3.1

How Unit Testing Principles, Practices, and Patterns covers it

How deep it goes
Defines public and private APIs, explains leakage and encapsulation, and demonstrates refactoring without covering API versioning or protocols.
Examples
Uses User name normalization, Customer promotion discounts, and purchase operations to expose leaking state or multi-call APIs.
What it assumes
Assumes basic object-oriented programming and unit testing, while teaching access modifiers, observable behavior, and API leakage from first principles.
What you can do after
Evaluate/understand whether a public member represents client-observable behavior and refactor leaked implementation details behind private boundaries.
How it connects
Connects APIs to observable behavior, implementation details, encapsulation, unit testing, black-box testing, and the Single Responsibility principle.

Also explained in

Compare how 44 books explain contract →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Unit Testing Principles, Practices, and Patterns. The section links point to the parts of the book it draws on.