Conceptcore
Abstract data type
Also called ADT, data abstraction, abstract type, abstract data types, cluster.
An abstract data type is a type defined by its operations and their rules, not by how its values are stored. A stack is push, pop and top, whether an array or a list holds it.
- Applies to
- core-languages
Idea
A program that uses a stack needs three things: put a value on top, look at the top value, and take it off. It does not need to know whether the stack keeps its values in an array or in linked nodes. An abstract data type (ADT) is a type that is defined in this way, by its operations and the rules that they follow. The code that uses the type sees only the operations. The code that implements it chooses a representation and can change it later.
class ArrayStack:
def __init__(self):
self._items = [] # the representation: a Python list
def push(self, v):
self._items.append(v)
def pop(self):
return self._items.pop()
def is_empty(self):
return not self._items
class LinkedStack:
def __init__(self):
self._top = None # the representation: (value, rest) pairs
def push(self, v):
self._top = (v, self._top)
def pop(self):
v, self._top = self._top
return v
def is_empty(self):
return self._top is None
def drain(stack): # client code: uses only the operations
for v in (1, 2, 3):
stack.push(v)
out = []
while not stack.is_empty():
out.append(stack.pop())
return out
for s in (ArrayStack(), LinkedStack()):
print(type(s).__name__, drain(s))
ArrayStack [3, 2, 1]
LinkedStack [3, 2, 1]
The function drain works with both classes, because both give the same operations with the same rules: the last value pushed is the first value popped. The underscore in _items and _top tells other code not to touch the representation.
How it works
Values and operations. NIST defines an ADT as "A set of data values and associated operations that are precisely specified independent of any particular implementation"1. Wikipedia describes it "from the point of view of a user of the data, specifically in terms of possible values, possible operations on data of this type, and the behavior of these operations"2. A data structure is the other side: it is a concrete representation, from the point of view of an implementer2.
Rules for the operations. The operations must follow rules, and the rules can be written as equations. For a stack, NIST gives two axioms: popOff(push(v, S)) = S and top(push(v, S)) = v1. "Since the data values and operations are defined with mathematical precision, rather than as an implementation in a computer language, we may reason about effects of the operations"1. Any implementation that keeps the rules is a correct stack.
Constructors and selectors. SICP builds a rational number type from three procedures. The constructor make-rat makes a value, and the selectors numer and denom read its parts. "The interface between these two parts of our system will be a set of procedures, called selectors and constructors, that implement the abstract data in terms of the concrete representation"3. The arithmetic procedures use only these three, so a change to the representation, such as reducing the fraction in make-rat, needs no change elsewhere: SICP calls the separating layers "abstraction barriers"3.
Hiding the representation. "In order to prevent clients from depending on the implementation, an ADT is often packaged as an opaque data type or handle of some sort"2. An opaque type is "a data type whose concrete data structure is not defined in an interface"4, so other code can use its values only through the operations. Each language has its own way to hide the representation, as the next section shows. See opaque type and encapsulation and visibility.
One type, many implementations. "Usually, there are many ways to implement the same ADT, using several different concrete data structures"2. The Java collections framework is built on this. Its interfaces, such as List, are the abstract types, and "Because the various implementations of each interface are interchangeable, programs can be tuned by switching implementations"5. Code that is written to the interface keeps working when the implementation changes. See collection interfaces.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Idiom | |
| C++ | Native | |
| Java | Native | |
| C | Idiom | |
| C# | Native | |
| JavaScript | Native | |
| TypeScript | Native | |
| Go | Native | |
| Rust | Native | |
| Kotlin | Native | Kotlin has interfaces and classes with private properties. No example file exists because kotlinc is not installed. |
| SQL | Does not apply | A query works on tables and views, not on abstract types in program code. |
| Bash | Idiom | |
| PowerShell | Native | PowerShell has classes with hidden members, and modules that export only some functions. No example file exists because pwsh is not installed. |
| HTML | Does not apply | HTML has no types. |
| CSS | Does not apply | CSS has no types. |
| Regular expressions | Does not apply | A regular expression has no types. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | idiom | a class with the operations as methods; a leading underscore marks the representation; abc and Protocol for the interface |
| JavaScript | native | a class with #private fields, or a closure that keeps the representation |
| TypeScript | native | an interface for the operations, and a class with private or #private fields |
| Java | native | an interface for the operations, and classes with private fields |
| Kotlin | native | an interface, and classes with private properties |
| C# | native | an interface, and classes with private fields |
| Go | native | an interface, and a struct whose fields are not exported from its package |
| Rust | native | a trait for the operations, and a struct whose fields are private to its module |
| C | idiom | an incomplete struct type in the header, functions that take a pointer to it, and the struct body in the .c file |
| C++ | native | a class with private members; an abstract base class with pure virtual functions for the interface |
| Bash | idiom | a set of functions that work on one array; nothing stops other code from changing the array |
| PowerShell | native | a class with hidden members, or a module that exports only its functions |
| SQL | n/a | a query works on tables and views, not on abstract types in program code |
| Regex | n/a | a pattern has no types |
| HTML | n/a | HTML has no types |
| CSS | n/a | CSS has no types |
Most languages can hide a representation, but they do it at different levels. Java, C#, C++ and JavaScript hide a field in a class. Go hides a name in a package: "An identifier is exported if both: the first character of the identifier's name is a Unicode uppercase letter"6 and it is declared at package level or is a field or a method. Rust hides a field in a module, because "struct fields follow the general rule of everything being private by default unless annotated with pub"7. In C, the header declares the type without its fields. Python and Bash do not enforce the barrier.
The example files define a stack ADT in each language. Each file has the interface, two implementations, one on an array and one on linked nodes, and one client function that works with both. Python uses two classes and duck typing. JavaScript uses #private fields. TypeScript, Java and C# use an interface. Go uses an interface and two structs. Rust uses a trait and keeps the fields private in a module. C keeps the struct body behind a pointer. C++ uses an abstract base class. Bash has one implementation, a set of functions over a named array.
from typing import Protocol
class Stack(Protocol):
def push(self, v: int) -> None: ...
def pop(self) -> int: ...
def is_empty(self) -> bool: ...
class ArrayStack:
def __init__(self) -> None:
self._items: list[int] = []
def push(self, v: int) -> None:
self._items.append(v)
def pop(self) -> int:
return self._items.pop()
def is_empty(self) -> bool:
return not self._items
class LinkedStack:
def __init__(self) -> None:
self._top: tuple[int, object] | None = None
def push(self, v: int) -> None:
self._top = (v, self._top)
def pop(self) -> int:
assert self._top is not None
v, self._top = self._top
return v
def is_empty(self) -> bool:
return self._top is None
def drain(s: Stack) -> str:
for v in (1, 2, 3):
s.push(v)
out = []
while not s.is_empty():
out.append(str(s.pop()))
return " ".join(out)
for s in (ArrayStack(), LinkedStack()):
print(f"{type(s).__name__}: {drain(s)}")
ArrayStack: 3 2 1
LinkedStack: 3 2 1
- Verdict: idiom. A class gives the operations as methods.
Protocolnames the interface for a type checker, and neither class inherits from it. - The leading underscore in
_itemsand_topmarks the representation as private by convention. Python does not stop other code from using it.
#include <iostream>
#include <memory>
#include <string>
#include <vector>
class Stack {
public:
virtual ~Stack() = default;
virtual void push(int v) = 0;
virtual int pop() = 0;
virtual bool empty() const = 0;
};
class ArrayStack final : public Stack {
public:
void push(int v) override { items_.push_back(v); }
int pop() override { int v = items_.back(); items_.pop_back(); return v; }
bool empty() const override { return items_.empty(); }
private:
std::vector<int> items_;
};
class LinkedStack final : public Stack {
public:
void push(int v) override { top_ = std::make_unique<Cell>(Cell{v, std::move(top_)}); }
int pop() override { int v = top_->v; top_ = std::move(top_->rest); return v; }
bool empty() const override { return top_ == nullptr; }
private:
struct Cell {
int v;
std::unique_ptr<Cell> rest;
};
std::unique_ptr<Cell> top_;
};
std::string drain(Stack& s) {
for (int v = 1; v <= 3; ++v) s.push(v);
std::string out;
while (!s.empty()) {
if (!out.empty()) out += ' ';
out += std::to_string(s.pop());
}
return out;
}
int main() {
ArrayStack a;
LinkedStack l;
std::cout << "ArrayStack: " << drain(a) << '\n';
std::cout << "LinkedStack: " << drain(l) << '\n';
}
ArrayStack: 3 2 1
LinkedStack: 3 2 1
- Verdict: native. The abstract base class
Stackhas only pure virtual functions, so it names the operations. Each class keeps its representation inprivatemembers. - A template that takes the stack type as a parameter would avoid the virtual calls. See the page on templates and generics.
import java.util.ArrayList;
import java.util.StringJoiner;
public class Main {
interface Stack<T> {
void push(T v);
T pop();
boolean isEmpty();
}
static final class ArrayStack<T> implements Stack<T> {
private final ArrayList<T> items = new ArrayList<>();
public void push(T v) { items.add(v); }
public T pop() { return items.remove(items.size() - 1); }
public boolean isEmpty() { return items.isEmpty(); }
}
static final class LinkedStack<T> implements Stack<T> {
private record Cell<T>(T v, Cell<T> rest) {}
private Cell<T> top;
public void push(T v) { top = new Cell<>(v, top); }
public T pop() { T v = top.v(); top = top.rest(); return v; }
public boolean isEmpty() { return top == null; }
}
static String drain(Stack<Integer> s) {
for (int v = 1; v <= 3; v++) s.push(v);
StringJoiner out = new StringJoiner(" ");
while (!s.isEmpty()) out.add(String.valueOf(s.pop()));
return out.toString();
}
public static void main(String[] args) {
for (Stack<Integer> s : java.util.List.of(new ArrayStack<Integer>(), new LinkedStack<Integer>())) {
System.out.println(s.getClass().getSimpleName() + ": " + drain(s));
}
}
}
ArrayStack: 3 2 1
LinkedStack: 3 2 1
- Verdict: native. An interface names the operations, and each class keeps its representation in
privatefields. draintakes the interface type, so it works with any class that implementsStack.
#include <stdio.h>
#include <stdlib.h>
/* stack.h: the interface. The struct has no body here. */
typedef struct stack stack;
stack *stack_new(void);
void stack_push(stack *s, int v);
int stack_pop(stack *s);
int stack_is_empty(const stack *s);
void stack_free(stack *s);
/* client code: uses only the functions above */
static void drain(const char *name, stack *s) {
for (int v = 1; v <= 3; v++) {
stack_push(s, v);
}
printf("%s:", name);
while (!stack_is_empty(s)) {
printf(" %d", stack_pop(s));
}
printf("\n");
}
/* stack.c: one implementation, on linked cells. */
struct cell {
int v;
struct cell *rest;
};
struct stack {
struct cell *top;
};
stack *stack_new(void) {
stack *s = malloc(sizeof *s);
if (s == NULL) {
exit(1);
}
s->top = NULL;
return s;
}
void stack_push(stack *s, int v) {
struct cell *c = malloc(sizeof *c);
if (c == NULL) {
exit(1);
}
c->v = v;
c->rest = s->top;
s->top = c;
}
int stack_pop(stack *s) {
struct cell *c = s->top;
int v = c->v;
s->top = c->rest;
free(c);
return v;
}
int stack_is_empty(const stack *s) { return s->top == NULL; }
void stack_free(stack *s) {
while (!stack_is_empty(s)) {
stack_pop(s);
}
free(s);
}
int main(void) {
stack *s = stack_new();
drain("LinkedStack", s);
stack_free(s);
return 0;
}
LinkedStack: 3 2 1
- Verdict: idiom. The header declares
struct stackwithout its fields, so code that includes only the header can hold astack *but cannot look inside it. The.cfile gives the body. - A C program has one implementation for each set of function names. A second implementation needs other names, or a struct of function pointers.
- This example puts the header, the client and the implementation in one file.
draincomes before the struct body, so the compiler stops it from reading the fields.
using System;
using System.Collections.Generic;
static string Drain(IStack<int> s)
{
for (int v = 1; v <= 3; v++) s.Push(v);
var output = new List<int>();
while (!s.IsEmpty) output.Add(s.Pop());
return string.Join(" ", output);
}
IStack<int>[] stacks = { new ArrayStack<int>(), new LinkedStack<int>() };
foreach (var s in stacks)
{
Console.WriteLine($"{s.GetType().Name.Split('`')[0]}: {Drain(s)}");
}
interface IStack<T>
{
void Push(T v);
T Pop();
bool IsEmpty { get; }
}
sealed class ArrayStack<T> : IStack<T>
{
private readonly List<T> items = new();
public void Push(T v) => items.Add(v);
public T Pop() { var v = items[items.Count - 1]; items.RemoveAt(items.Count - 1); return v; }
public bool IsEmpty => items.Count == 0;
}
sealed class LinkedStack<T> : IStack<T>
{
private sealed record Cell(T V, Cell? Rest);
private Cell? top;
public void Push(T v) => top = new Cell(v, top);
public T Pop() { var c = top!; top = c.Rest; return c.V; }
public bool IsEmpty => top is null;
}
ArrayStack: 3 2 1
LinkedStack: 3 2 1
- Verdict: native. The interface
IStack<T>names the operations, and each class keeps its representation inprivatemembers. GetType().Nameof a generic class ends with a backtick and the number of type parameters, so the code cuts the name there.
class ArrayStack {
#items = [];
push(v) { this.#items.push(v); }
pop() { return this.#items.pop(); }
isEmpty() { return this.#items.length === 0; }
}
class LinkedStack {
#top = null;
push(v) { this.#top = { v, rest: this.#top }; }
pop() { const { v, rest } = this.#top; this.#top = rest; return v; }
isEmpty() { return this.#top === null; }
}
function drain(s) {
for (const v of [1, 2, 3]) s.push(v);
const out = [];
while (!s.isEmpty()) out.push(s.pop());
return out.join(" ");
}
for (const s of [new ArrayStack(), new LinkedStack()]) {
console.log(`${s.constructor.name}: ${drain(s)}`);
}
console.log(Object.keys(new ArrayStack()).length);
ArrayStack: 3 2 1
LinkedStack: 3 2 1
0
- Verdict: native. A field whose name starts with
#is private to the class. Code outside the class cannot read it, andObject.keysdoes not list it. - JavaScript has no interface declaration.
drainworks with any object that haspush,popandisEmpty.
interface Stack<T> {
push(v: T): void;
pop(): T | undefined;
isEmpty(): boolean;
}
class ArrayStack<T> implements Stack<T> {
#items: T[] = [];
push(v: T): void { this.#items.push(v); }
pop(): T | undefined { return this.#items.pop(); }
isEmpty(): boolean { return this.#items.length === 0; }
}
type Cell<T> = { v: T; rest: Cell<T> | null };
class LinkedStack<T> implements Stack<T> {
#top: Cell<T> | null = null;
push(v: T): void { this.#top = { v, rest: this.#top }; }
pop(): T | undefined {
if (this.#top === null) return undefined;
const { v, rest } = this.#top;
this.#top = rest;
return v;
}
isEmpty(): boolean { return this.#top === null; }
}
function drain(s: Stack<number>): string {
for (const v of [1, 2, 3]) s.push(v);
const out: number[] = [];
while (!s.isEmpty()) out.push(s.pop()!);
return out.join(" ");
}
const stacks: Stack<number>[] = [new ArrayStack<number>(), new LinkedStack<number>()];
for (const s of stacks) {
console.log(`${s.constructor.name}: ${drain(s)}`);
}
ArrayStack: 3 2 1
LinkedStack: 3 2 1
- Verdict: native. The interface
Stack<T>names the operations, and each classimplementsit. The#fields keep the representation private when the program runs. draintakes aStack<number>, so the checker allows only the three operations inside it.
package main
import (
"fmt"
"strconv"
"strings"
)
// Stack is the abstract type: only the operations.
type Stack interface {
Push(v int)
Pop() int
IsEmpty() bool
}
// The field names start with a lower-case letter, so code in
// other packages cannot use them.
type ArrayStack struct{ items []int }
func (s *ArrayStack) Push(v int) { s.items = append(s.items, v) }
func (s *ArrayStack) Pop() int {
v := s.items[len(s.items)-1]
s.items = s.items[:len(s.items)-1]
return v
}
func (s *ArrayStack) IsEmpty() bool { return len(s.items) == 0 }
type cell struct {
v int
rest *cell
}
type LinkedStack struct{ top *cell }
func (s *LinkedStack) Push(v int) { s.top = &cell{v, s.top} }
func (s *LinkedStack) Pop() int {
v := s.top.v
s.top = s.top.rest
return v
}
func (s *LinkedStack) IsEmpty() bool { return s.top == nil }
func drain(s Stack) string {
for v := 1; v <= 3; v++ {
s.Push(v)
}
var out []string
for !s.IsEmpty() {
out = append(out, strconv.Itoa(s.Pop()))
}
return strings.Join(out, " ")
}
func main() {
fmt.Println("ArrayStack:", drain(&ArrayStack{}))
fmt.Println("LinkedStack:", drain(&LinkedStack{}))
}
ArrayStack: 3 2 1
LinkedStack: 3 2 1
- Verdict: native. An interface names the operations, and a type satisfies it by having the methods. Privacy works at the level of the package: a name that starts with a lower-case letter is not exported.
- This example is one
mainpackage, so the hiding does not show here. In a library,itemsandtopwould be invisible to the code that imports it.
mod stacks {
pub trait Stack {
fn push(&mut self, v: i32);
fn pop(&mut self) -> Option<i32>;
fn is_empty(&self) -> bool;
}
#[derive(Default)]
pub struct ArrayStack {
items: Vec<i32>, // private to the module
}
impl Stack for ArrayStack {
fn push(&mut self, v: i32) { self.items.push(v); }
fn pop(&mut self) -> Option<i32> { self.items.pop() }
fn is_empty(&self) -> bool { self.items.is_empty() }
}
struct Cell {
v: i32,
rest: Option<Box<Cell>>,
}
#[derive(Default)]
pub struct LinkedStack {
top: Option<Box<Cell>>,
}
impl Stack for LinkedStack {
fn push(&mut self, v: i32) {
let rest = self.top.take();
self.top = Some(Box::new(Cell { v, rest }));
}
fn pop(&mut self) -> Option<i32> {
self.top.take().map(|c| {
let Cell { v, rest } = *c;
self.top = rest;
v
})
}
fn is_empty(&self) -> bool { self.top.is_none() }
}
}
use stacks::{ArrayStack, LinkedStack, Stack};
fn drain(s: &mut dyn Stack) -> String {
for v in 1..=3 {
s.push(v);
}
let mut out = Vec::new();
while let Some(v) = s.pop() {
out.push(v.to_string());
}
out.join(" ")
}
fn main() {
println!("ArrayStack: {}", drain(&mut ArrayStack::default()));
println!("LinkedStack: {}", drain(&mut LinkedStack::default()));
}
ArrayStack: 3 2 1
LinkedStack: 3 2 1
- Verdict: native. A trait names the operations. The fields
itemsandtophave nopub, so only code inside the modulestackscan use them. - Code outside the module cannot write
ArrayStack { items: vec![] }, so it usesArrayStack::default()to make a value.
# The operations. The representation is the array named in $1.
stack_push() { local -n s=$1; s+=("$2"); }
stack_pop() { local -n s=$1; REPLY=${s[-1]}; unset 's[-1]'; }
stack_is_empty() { local -n s=$1; (( ${#s[@]} == 0 )); }
nums=()
for v in 1 2 3; do stack_push nums "$v"; done
out=()
while ! stack_is_empty nums; do
stack_pop nums
out+=("$REPLY")
done
echo "ArrayStack: ${out[*]}"
ArrayStack: 3 2 1
- Verdict: idiom. A set of functions works on one array, and the code that uses the stack calls only the functions.
local -nmakessa name for the array that the caller passes. - Nothing hides the array. Any code can change
numsdirectly, so the barrier is only a habit. stack_popreturns its value inREPLY, because$(stack_pop nums)would run in a subshell and its change to the array would be lost.
Variations and related ideas
- Classes as ADTs. "Modern object-oriented languages, such as C++ and Java, support a form of abstract data types"2. A class holds the representation in private fields and gives the operations as methods. JavaScript private elements "get created by using a hash # prefix and cannot be legally referenced outside of the class"8. In C#, a
privatemember is one that "Only code declared in the same class or struct can access"9. In C++, "A private member of a class is only accessible to the members and friends of that class"10. - Modules as ADTs. A module can export a type name and its functions but not the fields of the type. Go, Rust and the C header work this way. One module then holds the whole implementation, and the type can have operations that look at two values at once, such as a merge of two sets.
- Interfaces. An interface, a trait or an abstract base class names the operations without a representation. Python's abstract base classes "can be used to test whether a class provides a particular interface"11. See interfaces.
- Built-in ADTs. Some built-in types are ADTs: the language says what their operations do, but not how they are stored. Wikipedia names the arrays of Awk, Lua and Perl, "which can be regarded as an implementation of the abstract list"2.
Pitfalls
- Abstract data type and algebraic data type. Both are written ADT, but they are opposite ideas. An abstract data type hides its representation behind operations. An algebraic data type shows its representation: its values are built from named cases, and code takes them apart with pattern matching. Write the full name when the meaning is not clear.
- A leaky representation. A method that returns the internal list lets the caller change the stack without
pushorpop. Return a copy, a read-only view or an iterator. - A barrier only by convention. Python does not hide
_items. The tutorial says that a name with a leading underscore "should be treated as a non-public part of the API"12, but code outside the class can still read and change it. Bash has no barrier at all. - Rules that are not written down. Most languages check only the names and the types of the operations. "Most mainstream computer languages do not directly support formally specifying ADTs"2. A class can have
pushandpopand still break the stack rules. Write the rules in the documentation and test them. - The limits of the representation. An implementation can fail where the abstract type does not. Integers as an ADT have no largest value, but "in a computer, integers are most commonly represented as fixed-width 32-bit or 64-bit binary numbers"2, so they overflow.
Cost
A call through an interface goes to code that the caller does not know, so the compiler cannot inline it. In C, an opaque struct must live behind a pointer, because the code that uses it does not know its size. A generic function in Rust or C++ avoids the indirect call, because the compiler makes a copy of it for each concrete type. See templates and generics. The larger gain is that the representation can change for speed without any change to the code that uses it2.
History
"ADTs were first proposed by Barbara Liskov and Stephen N. Zilles in 1974, as part of the development of the CLU language"2. Their paper was "Programming with abstract data types", in the proceedings of the ACM SIGPLAN Symposium on Very High Level Languages2. CLU first appeared in 197513. Its "key addition was the concept of a cluster"13: "A cluster implements a data abstraction, which is a set of objects and a set of primitive operations to create and manipulate those objects"13, and its representation type "is hidden from external clients"13. "Algebraic specification was an important subject of research in CS around 1980 and almost a synonym for abstract data types at that time"2.
References
- abstract data type, Dictionary of Algorithms and Data Structures, NIST, Definition; Note
- Abstract data type, Wikipedia, Introduction; History; Implementation
- 2.1 Introduction to Data Abstraction, Structure and Interpretation of Computer Programs, 2.1; 2.1.2 Abstraction Barriers
- Opaque data type, Wikipedia, Introduction
- Collections Framework Overview, Java SE 21, Introduction
- The Go Programming Language Specification, Exported identifiers
- Paths for Referring to an Item in the Module Tree, The Rust Programming Language, Making Structs and Enums Public
- Private elements, MDN Web Docs, Introduction
- Access Modifiers, C# programming guide, Introduction
- Access specifiers, C++ reference, cppreference.com, Private member access
- collections.abc, Python 3.14 documentation, Introduction
- Classes, The Python Tutorial, 9.6 Private Variables
- CLU (programming language), Wikipedia, Introduction; Clusters
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag M1NV6B Edit this page History Report an error Markdown