Choosing a List or Tuple for an Interface
Sequences can represent a variable list of items or a fixed arrangement of fields. Their mutability and positional meaning are separate design choices.
- Source
- Anbloq
- Language
- English
- Created
- Updated
- Chapters
- 4
- Reading time
- 1 min
In this article4 chapters
Read fields by role
A coordinate returned as the pair (2, 7) has two roles, horizontal and vertical. A list of waypoints may contain any number of such pairs. A structured return value helps keep those layers separate.
Define who can modify the outer sequence
A caller receiving a list can append another element. A tuple's positions stay fixed, although its members may hold mutable objects. See tuples and mutable contents before choosing a tuple to promise an immutable result.[1]
Separate the shape of a value from its lifetime
A coordinate pair such as (12, 3) uses two fixed positions with known meanings. A path can hold a list of such pairs whose length grows as the route is traced. Returning a tuple for the path can promise that positions are fixed in the returned container. That promise does not make an inner list immutable. Test both adding to the outer sequence, where allowed, and changing an inner element. See immutable tuple shells.
Consider what users learn from the representation
If two integer positions mean row and column, their order may be confused when the grid is square. Named fields can expose the intended meanings. For an interface that accepts a sequence only so it can read values in order, callers can often supply either a tuple or a list. If the implementation needs to insert into the input, announce that requirement and specify who owns it. See input ownership in functions.