Chapter 33 Key Takeaways

Units Are Pascal's Module System

A unit is a separate .pas file with two sections: - Interface — public declarations (types, constants, procedure/function headers). No code bodies. - Implementation — private code, helper functions, and bodies for interface declarations.

The unit name must match the filename. A unit ends with end. (period).

The Uses Clause

  • Place units needed by interface declarations in the interface uses clause
  • Place units needed only by implementation code in the implementation uses clause
  • Implementation uses keeps transitive dependencies lower and can resolve circular references
  • Circular references in interface uses clauses are prohibited by the compiler

Initialization and Finalization

  • initialization runs automatically at program start, in dependency order
  • finalization runs at program exit, in reverse dependency order
  • Keep initialization minimal — defer complex setup to explicit procedures

Libraries

Type When Linked File Extension Pros Cons
Static Compile time .a / .lib Standalone executable Larger binary, must recompile
Dynamic Runtime .dll / .so Shared, updatable Runtime dependency

Namespace Management

  • Qualified identifiers resolve conflicts: UnitName.Identifier
  • Minimize the interface — fewer public symbols means fewer potential collisions
  • Prefix public names in libraries to avoid conflicts

Design Principles

Principle Goal Rule of Thumb
High Cohesion Each unit does one thing If you need "and" to describe it, split it
Low Coupling Minimal inter-unit dependencies Pass data through parameters, not globals
Dependency Inversion Depend on abstractions Core modules should not know about storage/UI
Acyclic Dependencies No circular dependency chains If A needs B and B needs A, extract shared types

PennyWise Architecture

Four units with clear responsibilities: - FinanceCore — domain model (types, calculations). No dependencies. - FinanceDB — data persistence. Depends on FinanceCore. - FinanceReports — report generation. Depends on FinanceCore. - FinanceUI — user interface. Depends on FinanceCore + FinanceReports.

The dependency graph is a DAG with FinanceCore at the foundation.

Practical Rules

  1. One unit per major abstraction
  2. Keep interfaces small — export only what clients need
  3. Hide implementation details aggressively
  4. Group by feature, not by type
  5. Target 100–1,000 lines per unit
  6. The main program should be a thin coordinator