Hiding what should be hidden
In 1972 David Parnas argued that a program should be divided into modules not by the steps of its algorithm but by its design decisions: each module hides one decision that might change (how data is stored, which device is used, what format a file has) behind an interface that does not mention it. When the decision changes, only that module changes. The idea is now so widely accepted that it is easy to forget how rarely languages enforced it.
Ada was built around it. The package is Ada's unit of modularity, and it comes in two parts compiled separately: a specification that says what the package offers, and a body that says how. Clients see only the specification. A type can be declared private, so that clients can hold and pass its values but never look inside, and the compiler, not a naming convention, enforces the boundary. Change the body and the clients do not even need recompiling.
Packages work together with generics, Ada's templates: a package or subprogram written once with parameters such as "any element type" or "a capacity", and instantiated for each use. Ada's standard containers, its vectors, lists, maps and sets, are generic packages. Generics have been part of Ada since 1983, years before C++ templates became standard and decades before generics arrived in Java and Go.
Specifications, bodies and private types
Definition— Package specification and body
A package specification declares the types, constants, subprograms and exceptions that clients may use, and ends with an optional private part that clients cannot see. The package body contains the subprogram bodies and anything else the implementation needs. A client names the package in a with clause and can use only what the visible part of the specification declares.
Definition— Private type
A type declared type T is private; in the visible part, and completed in the private part, can be declared, assigned, compared for equality and passed to the package's subprograms by clients, but its components are invisible to them. A limited private type cannot even be assigned or compared, which suits values that must not be copied, such as a file handle or a lock.
Why is the full type in the specification at all, if clients cannot see it? Because the compiler needs its size to lay out clients' variables. The private part is visible to the compiler, but not to the programmers writing clients. The rule is: anything a client could depend on is in the visible part; everything else is in the private part or the body.
Packages can be nested inside other units, as in the single-file programs in this course, but in real projects they are library units, each in its own files:
| Unit | GNAT file name | Contains |
|---|---|---|
package Fractions (specification) | fractions.ads | the interface |
package body Fractions | fractions.adb | the implementation |
package Fractions.Text (a child package) | fractions-text.ads, fractions-text.adb | an extension that may see Fractions' private part in its own private part and body |
procedure Main | main.adb | the main program |
Child packages extend a package without editing it: Fractions.Text might add parsing and formatting, and because it is a child it can use the private representation in its body. Large Ada systems are trees of packages, and the standard library is too: Ada.Strings.Unbounded is a child of Ada.Strings, which is a child of Ada.
A package body can end with a begin part of statements that run once, before the main program, to initialise the package's state. This is called elaboration, and the binder you met in Lesson 1 works out an order in which every package can be elaborated after the packages it depends on.
A package that keeps its promises
This package provides exact fractions. Its design decision is the representation: a numerator and a positive denominator, always in lowest terms. Because the type is private, the only way to create a fraction is through the package's own operations, so the rule can never be broken, and equality can simply compare components.
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Strings; use Ada.Strings;
with Ada.Strings.Fixed; use Ada.Strings.Fixed;
procedure Main is
-- The specification: what clients may see and use.
package Fractions is
type Fraction is private;
function "/" (Numerator, Denominator : Integer) return Fraction;
function "+" (Left, Right : Fraction) return Fraction;
function "*" (Left, Right : Fraction) return Fraction;
function Image (F : Fraction) return String;
Division_By_Zero : exception;
private
-- Visible to the compiler, hidden from clients.
-- Always in lowest terms, with a positive denominator.
type Fraction is record
Num : Integer := 0;
Den : Positive := 1;
end record;
end Fractions;
-- The body: how it is done. Clients never depend on it.
package body Fractions is
function Gcd (A, B : Natural) return Natural is
(if B = 0 then A else Gcd (B, A mod B));
function "/" (Numerator, Denominator : Integer) return Fraction is
G : Natural;
begin
if Denominator = 0 then
raise Division_By_Zero;
end if;
G := Gcd (abs Numerator, abs Denominator);
if Denominator < 0 then
return (Num => (-Numerator) / G, Den => (-Denominator) / G);
else
return (Num => Numerator / G, Den => Denominator / G);
end if;
end "/";
function "+" (Left, Right : Fraction) return Fraction is
((Left.Num * Right.Den + Right.Num * Left.Den) / (Left.Den * Right.Den));
function "*" (Left, Right : Fraction) return Fraction is
((Left.Num * Right.Num) / (Left.Den * Right.Den));
function Image (F : Fraction) return String is
Num : constant String := Trim (F.Num'Image, Left);
Den : constant String := Trim (F.Den'Image, Left);
begin
return (if F.Den = 1 then Num else Num & "/" & Den);
end Image;
end Fractions;
use Fractions;
Half : constant Fraction := 1 / 2;
Third : constant Fraction := 1 / 3;
begin
Put_Line ("1/2 + 1/3 = " & Image (Half + Third));
Put_Line ("2/4 = 1/2 ? " & Boolean'Image (2 / 4 = Half));
Put_Line ("3/-6 = " & Image (3 / (-6)));
Put_Line ("1/2 * 4 = " & Image (Half * (4 / 1)));
Put_Line ("1/0 = " & Image (1 / 0));
exception
when Division_By_Zero =>
Put_Line ("Division_By_Zero raised");
end Main;It prints:
1/2 + 1/3 = 5/6
2/4 = 1/2 ? TRUE
3/-6 = -1/2
1/2 * 4 = 2
Division_By_Zero raisedSeveral details are worth studying:
- Operators are ordinary functions with quoted names. Defining
"/"taking two integers and returning aFractionmeans1 / 2builds a fraction wherever aFractionis expected, while7 / 2in anIntegercontext still means integer division. The compiler chooses by the expected type. 2 / 4 = Halfis true because every fraction is normalised when it is made. If clients could write(Num => 2, Den => 4)directly,"="would give the wrong answer; the private type is what makes the simple equality correct.- Inside the body, the private components are visible and used freely.
Gcdis declared only in the body, so it is not part of the interface and clients cannot call it. use Fractions;makes all the package's names visible. A more selective alternative isuse type Fractions.Fraction;, which makes only the type's operators visible, soHalf + Thirdworks while other names stay qualified, as inFractions.Image (X). Many style guides prefer it.
A client that tries to look inside is stopped by the compiler. In a shortened version of this program, the statement F.Den := 7; in Main gave:
main.adb:18:04: error: invalid prefix in selected component "F"Generics
Definition— Generic unit
A generic unit is a subprogram or package with formal parameters: types, values, objects, subprograms or packages that are supplied when it is instantiated. Each instantiation, such as package Int_Stacks is new Bounded_Stacks (Integer, 3);, creates an ordinary package or subprogram.
The formal type tells the generic what it may assume about the actual type, and so which types are allowed:
| Formal | Accepts | The generic may use |
|---|---|---|
type T is private; | any type with assignment and = | assignment, = |
type T is limited private; | any type at all | nothing but what other formals provide |
type T is (<>); | any discrete type | 'First, 'Last, 'Succ, for loops |
type T is range <>; | any signed integer type | arithmetic |
type T is digits <>; | any floating-point type | real arithmetic |
with function "<" (L, R : T) return Boolean is <>; | a function, by default the visible "<" for T | calling it |
A generic subprogram looks like this:
generic
type Item is private;
with function "<" (Left, Right : Item) return Boolean is <>;
function Generic_Max (A, B : Item) return Item;
function Generic_Max (A, B : Item) return Item is (if A < B then B else A);
function Max is new Generic_Max (Float); -- "<" for Float is found by defaultUnlike C++ templates, an Ada generic is checked once, when it is compiled, against its formal parameters: if the body uses an operation that the formals do not promise, the generic itself is rejected, so an instantiation can never fail with an error deep inside someone else's code. The contract between a generic and its users is its formal part.
A generic bounded stack
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;
procedure Main is
-- A generic package: a template with parameters, instantiated later.
generic
type Element is private; -- any type with assignment and "="
Capacity : Positive;
package Bounded_Stacks is
type Stack is limited private; -- limited: no copying, no "="
Overflow, Underflow : exception;
procedure Push (S : in out Stack; E : Element);
procedure Pop (S : in out Stack; E : out Element);
function Is_Empty (S : Stack) return Boolean;
function Size (S : Stack) return Natural;
private
type Element_Array is array (1 .. Capacity) of Element;
type Stack is record
Items : Element_Array;
Top : Natural := 0;
end record;
end Bounded_Stacks;
package body Bounded_Stacks is
procedure Push (S : in out Stack; E : Element) is
begin
if S.Top = Capacity then
raise Overflow;
end if;
S.Top := S.Top + 1;
S.Items (S.Top) := E;
end Push;
procedure Pop (S : in out Stack; E : out Element) is
begin
if S.Top = 0 then
raise Underflow;
end if;
E := S.Items (S.Top);
S.Top := S.Top - 1;
end Pop;
function Is_Empty (S : Stack) return Boolean is (S.Top = 0);
function Size (S : Stack) return Natural is (S.Top);
end Bounded_Stacks;
-- Two instantiations: two different packages from one template.
package Char_Stacks is new Bounded_Stacks (Element => Character, Capacity => 100);
package Int_Stacks is new Bounded_Stacks (Integer, 3);
-- Are the brackets in Text balanced?
function Balanced (Text : String) return Boolean is
use Char_Stacks;
Open : Stack;
Top : Character;
begin
for C of Text loop
case C is
when '(' | '[' | '{' =>
Push (Open, C);
when ')' | ']' | '}' =>
if Is_Empty (Open) then
return False;
end if;
Pop (Open, Top);
if (Top = '(' and C /= ')') or else (Top = '[' and C /= ']')
or else (Top = '{' and C /= '}')
then
return False;
end if;
when others =>
null;
end case;
end loop;
return Is_Empty (Open);
end Balanced;
procedure Check (Text : String) is
begin
Put_Line (Text & " balanced? " & Balanced (Text)'Image);
end Check;
Numbers : Int_Stacks.Stack;
begin
Check ("f(a[i]) + {x}");
Check ("(]");
Check ("((x)");
for I in 1 .. 4 loop
Int_Stacks.Push (Numbers, I * 10);
Put_Line ("pushed" & Integer'Image (I * 10));
end loop;
exception
when Int_Stacks.Overflow =>
Put_Line ("Overflow after" & Int_Stacks.Size (Numbers)'Image & " items");
end Main;It prints:
f(a[i]) + {x} balanced? TRUE
(] balanced? FALSE
((x) balanced? FALSE
pushed 10
pushed 20
pushed 30
Overflow after 3 itemsBounded_Stacks takes a type and a capacity. Char_Stacks and Int_Stacks are two separate packages made from it, each with its own Stack type and its own Overflow exception: notice the handler names Int_Stacks.Overflow. The Stack type is limited private, so clients cannot copy a stack by accident or compare two stacks. The capacity is fixed, and the storage is part of the Stack object itself, so this stack never allocates memory: exactly the style used in embedded and safety-critical code, where the heap is often forbidden.
The standard containers
Since Ada 2005 the standard library has a containers library of generic packages: Vectors, Doubly_Linked_Lists, Hashed_Maps, Ordered_Maps, Hashed_Sets, Ordered_Sets, Multiway_Trees and more. Each comes in variants: Indefinite_ versions hold elements of types whose size varies, such as String, and Bounded_ versions (Ada 2012) use fixed storage.
pragma Ada_2022;
with Ada.Text_IO; use Ada.Text_IO;
with Ada.Characters.Handling; use Ada.Characters.Handling;
with Ada.Containers.Vectors;
with Ada.Containers.Indefinite_Ordered_Maps;
procedure Main is
-- Instantiate the standard library's generic containers.
package Word_Counts is new Ada.Containers.Indefinite_Ordered_Maps
(Key_Type => String, Element_Type => Positive);
package Integer_Vectors is new Ada.Containers.Vectors
(Index_Type => Positive, Element_Type => Integer);
package Sorting is new Integer_Vectors.Generic_Sorting; -- uses "<" by default
Text : constant String :=
"the river and the hill and the sky over the river";
Counts : Word_Counts.Map;
Start : Positive := Text'First;
procedure Count (Word : String) is
Key : constant String := To_Lower (Word);
begin
if Counts.Contains (Key) then
Counts (Key) := Counts (Key) + 1;
else
Counts.Insert (Key, 1);
end if;
end Count;
Lengths : Integer_Vectors.Vector;
begin
for I in Text'Range loop
if Text (I) = ' ' then
Count (Text (Start .. I - 1));
Start := I + 1;
end if;
end loop;
Count (Text (Start .. Text'Last));
-- An ordered map iterates in key order.
for C in Counts.Iterate loop
Put_Line (Word_Counts.Key (C) & Word_Counts.Element (C)'Image);
Lengths.Append (Word_Counts.Key (C)'Length);
end loop;
Sorting.Sort (Lengths);
Put ("Word lengths, sorted:");
for L of Lengths loop
Put (L'Image);
end loop;
New_Line;
Put_Line ("Distinct words:" & Counts.Length'Image);
end Main;It prints:
and 2
hill 1
over 1
river 2
sky 1
the 4
Word lengths, sorted: 3 3 3 4 4 5
Distinct words: 6Word_Counts is a map from String keys to Positive counts. It must be the Indefinite_ variant because String values differ in length. Counts (Key) := Counts (Key) + 1; uses Ada 2012's user-defined indexing to update an element in place, and for C in Counts.Iterate walks the map in key order with a cursor C. Generic_Sorting is a generic package nested inside Vectors; instantiating it with no parameters picks up "<" for Integer by default. The calls Counts.Contains (Key) and Lengths.Append (…) use prefixed notation, a shorthand for Word_Counts.Contains (Counts, Key) that Ada 2005 introduced.
How Ada projects are organised
A real Ada project puts each library unit in its own files and is built by gprbuild, driven by a GNAT project file (.gpr). A minimal one looks like this:
project Weather is
for Source_Dirs use ("src");
for Object_Dir use "obj";
for Main use ("main.adb");
package Compiler is
for Default_Switches ("Ada") use ("-gnat2022", "-gnatwa", "-gnata");
end Compiler;
end Weather;gprbuild -P weather.gpr compiles every unit that changed, in the right order, and links the program. Because specifications and bodies are separate, changing a body recompiles only that body; changing a specification recompiles its clients too, which is one more reason to keep specifications small and stable.
Alire manages all of this for you. alr init --bin weather creates a project directory with a manifest, alire.toml, a project file and a src directory. alr build and alr run build and run it with the toolchain Alire installed. alr with aunit adds a dependency on the AUnit unit-testing library to the manifest, and the next build fetches it from the community index. alr search explores the index, and alr publish helps you contribute a crate of your own. Alire records the exact versions it chose in a lock file, so a colleague who clones your project gets the same build.
Teams also agree on conventions that the language leaves open: one package per design decision, specifications short enough to read in one sitting, use type rather than use for most packages, child packages for optional features, and a Tests hierarchy alongside the code. For style, GNAT's -gnaty checks and a formatter (AdaCore's gnatformat, or the older gnatpp) keep layout uniform.
Common misunderstandings
Misconception
"The private part is pointless, since anyone can read it." Anyone can read it, but no client can depend on it: code that uses a private component does not compile. That is the guarantee that lets you change the representation later with no effect on clients' correctness.
Misconception
"A .ads file is like a C header." A C header is pasted into each file that includes it, and nothing checks that the implementation matches. An Ada specification is compiled once, the body is checked against it, and the binder refuses to link units compiled against different versions of it.
Misconception
"Generics are expanded and checked at each use, like C++ templates." An Ada generic body is checked against its formal parameters when it is compiled, so instantiations do not produce errors from inside the generic. (GNAT does typically generate separate code for each instantiation, as C++ compilers do.)
Misconception
"Every instantiation of a generic shares the same exceptions and state." Each instantiation is a new package: Int_Stacks.Overflow and Char_Stacks.Overflow are different exceptions, and any variables declared in the generic package exist once per instantiation.
Exercises
All outputs below were checked by compiling and running the code with GNAT 14.
1. Packages and generics
Warm-upHumanIn the Fractions package, where is the helper function Gcd declared, and why?
2. Packages and generics
Warm-upComputationalUsing the Fractions package, what does Put_Line (Image (1 / 6 + 1 / 3)); print?
3. Packages and generics
CoreComputationalWhat does Put_Line (Image ((-2) / (-8))); print?
4. Packages and generics
CoreComputationalWhat line does Check ("([)]"); print in the stack program?
5. Packages and generics
CoreComputationalIn the stack program, Int_Stacks is instantiated with capacity 5 instead of 3. How many pushed lines does the program print now?
6. Packages and generics
StretchComputationalGiven the lesson's Generic_Max, a programmer writes function Min is new Generic_Max (Integer, ">");. What does Min (3, 9) return?
7. Packages and generics
Warm-upHumanUnder GNAT's default naming rules, what is the file name of the specification of the child package Weather.Sensors?
8. Packages and generics
CoreComputationalIn the containers program, Text is changed to "b a C a b A". What is the first line printed?
Further reading and resources
- Ada Reference Manual, section 7: Packages, and section 12: Generic unitsThe rules for specifications, bodies, private types and generics.
- Ada Reference Manual, Annex A.18: ContainersVectors, lists, hashed and ordered maps and sets, and their indefinite and bounded forms.
- Alire documentationCreating crates, adding dependencies with alr with, building, and publishing to the community index.
- GNAT User's Guide for Native PlatformsFile naming rules, the compilation model and GNAT project files.