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
-
Library Exports
- Definition: Selective visibility
- Example:
// lib/mylib.dart export 'src/implementation.dart' show PublicClass;
-
Private Across Libraries
- Definition: True encapsulation
- Example:
// In library A: class _Private {} // Inaccessible to B
-
Package Structure
- Definition: Standard layout
- Example:
my_package/ lib/ my_package.dart src/ implementation.dart
-
Dependency Privacy
- Definition: Between packages
- Example:
// Can't access _ members // from other packages
-
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
- Import Resolution: Analyzer checks access
- Compilation: Enforces library boundaries
- Package Layout: Convention over configuration
- 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.