liveBook · Manning

Contract

As explained in Grokking Data Structures

An API is a defined set of programmatic operations and interaction rules exposed by a software component.

Think of a light switch: you need to know how to turn it on and off, not whether it uses a toggle or buttons. A software contract works the same way. It defines the operations clients can use and what those operations do, while leaving room for different implementations. section 7.4

For an abstract data type, a contract includes more than method names. It specifies arguments, return types, behavior, and side effects: what each method accomplishes and whether it changes the collection. A bag, for example, supports insert(x) and iterate(). It permits duplicates, promises no iteration order, and does not offer search or removal. section 7.10

Keep the implementation behind the contract

A linked list might search internal nodes to find an order. Returning a node to the caller would expose mutable implementation details. Returning the order’s data instead lets clients use the result without depending on the Node class. The list can then change its implementation without breaking code that relies on its external interface. section 6.8

class Stack:
    def __init__(self):
        self._data = SinglyLinkedList()

A Stack can wrap a SinglyLinkedList while exposing only the stack operations clients need. Its underlying collection need not become part of the stack’s interface. section 8.9

A contract also helps distinguish essential operations from optional ones. A stack’s API includes push and pop; peek is a read-only operation sometimes provided beyond that standard API. A dictionary’s core interface covers inserting, retrieving by key, and deleting values, while methods such as finding minimum or maximum keys depend on the implementation. section 8.9 section 12.3

How Grokking Data Structures covers it

How deep it goes
Specifies method signatures, behavior, and side effects, then illustrates how an implementation can restrict an underlying collection’s interface.
Examples
Uses a light switch, bag operations, linked-list search, a stack wrapper, and dictionary operations to make contracts concrete.
What it assumes
Introduces interface specifications through simple container operations and an everyday light-switch analogy.
What you can do after
Build it from scratch by specifying permitted operations and their behavior while keeping internal nodes inaccessible to clients.
How it connects
Connects abstract data types, encapsulation, linked lists, stacks, and dictionaries through their public operations.

Also explained in

Compare how 44 books explain contract →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Grokking Data Structures. The section links point to the parts of the book it draws on.