Cross-library Privacy

Cross-library Privacy

About

  • Library Boundaries: Privacy enforcement
  • Exports: Controlling what’s exposed
  • Hiding Implementation: src/ convention
  • Package Design: Public vs private APIs

Main Topics

  1. Library Exports

    • Definition: Selective visibility
    • Example:
      // lib/mylib.dart
      export 'src/implementation.dart' show PublicClass;
  2. Private Across Libraries

    • Definition: True encapsulation
    • Example:
      // In library A:
      class _Private {} // Inaccessible to B
  3. Package Structure

    • Definition: Standard layout
    • Example:
      my_package/
        lib/
          my_package.dart
          src/
            implementation.dart
  4. Dependency Privacy

    • Definition: Between packages
    • Example:
      // Can't access _ members
      // from other packages
  5. Visibility Testing

    • Definition: Verifying privacy

    • Example:

      import 'package:other/other.dart';
      
      void main() {
        // var x = _Private(); // Compile error
      }

How to Use

  • API Design: Plan exports carefully
  • Implementation: Keep in src/
  • Documentation: Clearly mark public API
  • Versioning: Treat private as unstable

How It Works

  1. Import Resolution: Analyzer checks access
  2. Compilation: Enforces library boundaries
  3. Package Layout: Convention over configuration
  4. Pub: Respects privacy in dependencies

Example:

// Package structure:
// my_pkg/
//   lib/
//     my_pkg.dart        (exports)
//     src/
//       cache.dart       (private)
//       client.dart      (private)

// my_pkg.dart:
export 'src/client.dart' show PublicClient;

Conclusion

Cross-library privacy in Dart provides strong encapsulation between packages through rigorous enforcement of library boundaries. By properly organizing code into public exports and private implementations, package authors can maintain clean APIs while freely evolving their internal implementation details.