Sub topic 10
How languages express ADTs: interfaces, abstract classes, and modules
This chapter assumes you can read Python classes, know what an exception is, and have seen the Stack interface and the ListStack and LinkedStack implementations from earlier chapters. Here you will see which language features let you state an ADT's interface and keep its representation private.
What a language must provide
An ADT needs two things from a language:
- A way to write the interface, meaning the operation names and their promised behavior, apart from any storage choice.
- A way to keep the representation hidden, so clients cannot depend on it.
Languages cover these needs with different tools. Most offer more than one, and they differ in how strictly they enforce the rules.
| Mechanism | Typical languages | What it states | What it hides |
|---|---|---|---|
| Interface | Java, Go, TypeScript | Operation names and signatures only | Everything else, because it has no fields |
| Abstract class | Python, Java, C++ | Signatures, plus optional shared code | Subclass fields, if they are kept private |
| Module | OCaml, Ada, Python files | A public set of names | Names left out of the public set |
Abstract classes in Python
Python has no interface keyword. The usual substitute is an abstract base class, written with ABC and @abstractmethod. The Stack class below is the one from the earlier chapter.
from abc import ABC, abstractmethod
class Stack(ABC):
"""A last-in, first-out collection.
push(x) then pop() returns x.
pop() and peek() raise IndexError on an empty stack.
"""
@abstractmethod
def push(self, item):
"""Add item to the top of the stack."""
@abstractmethod
def pop(self):
"""Remove and return the top item."""
@abstractmethod
def peek(self):
"""Return the top item without removing it."""
@abstractmethod
def is_empty(self):
"""Return True if the stack has no items."""
try:
Stack()
except TypeError as error:
print(error)Python refuses to create an object from a class that still has abstract methods, so the last lines raise a TypeError. A subclass must implement every abstract method before you can use it. This catches a missing operation when you create the object, not when a client calls it.
An abstract class checks only the names. It cannot check that pop really returns the last item pushed. That promise lives in the docstring and in tests.
Hiding the representation
A language can enforce hiding to different degrees.
- Java and C++ have
privatefields. The compiler rejects outside access. - Python has a naming convention. A leading underscore, as in
_items, tells clients not to touch the field. The language does not stop them. - Modules hide at a larger scale. In Python, a module can list its public names in
__all__and keep helpers such as_Nodeout of that list.
# stacks.py
__all__ = ["Stack", "ListStack", "LinkedStack"]With this line, from stacks import * brings in the three public classes and leaves _Node behind. Clients still see only the interface.
Structural and nominal typing
Languages also differ in how they decide that a class "implements" an interface.
- Nominal typing requires a declaration. In Java, a class must say
implements Stack. - Structural typing accepts any class with the right methods. Go and TypeScript work this way. Python offers it through
typing.Protocol.
from typing import Protocol
class StackLike(Protocol):
def push(self, item): ...
def pop(self): ...
def peek(self): ...
def is_empty(self): ...With a protocol, ListStack would count as a StackLike without inheriting from it. Static type checkers such as mypy use this. Nominal typing makes the intent explicit. Structural typing keeps the client independent of the implementer's class hierarchy.
Choosing a mechanism
Use an abstract class when implementations share code or when you want an early error for a missing method. Use a protocol or an interface when you want clients and implementers to stay loosely coupled. Use a module boundary to decide which names the outside world sees at all. Many designs combine them: a module exports an interface, and the implementing classes stay private.
Exercise
A class ArrayStack defines push, pop, and peek but forgets is_empty, and it subclasses the abstract Stack from this chapter. When does Python report the problem, and what does it not report?
Show answer
Python raises a TypeError when you try to create an ArrayStack object, because the abstract method is_empty is unimplemented. It does not check that the methods you did write behave correctly, such as pop returning the most recently pushed item. Tests must check that.
Exercise
Why might you choose a Protocol over an abstract base class for a stack interface?
Show answer
A protocol lets any class with the right methods count as a stack without inheriting from a shared base class. This keeps clients independent of the implementer's class hierarchy, and it works with classes you cannot modify.