Use with Private Variables
Use with Private Variables
About
- Encapsulation: Hide implementation
- Controlled Access: Validate changes
- API Stability: Change internals safely
- Naming Convention:
_
prefix
Main Topics
-
Basic Encapsulation
-
Definition: Private fields with public accessors
-
Example:
class Wallet { double _balance = 0; double get balance => _balance; }
-
-
Validation
- Definition: Protect invariants
- Example:
set balance(double value) { if (value < 0) throw ArgumentError(); _balance = value; }
-
Read-only Exposure
-
Definition: Public getter, private setter
-
Example:
class Circle { final double _radius; double get radius => _radius; }
-
-
Derived State
- Definition: Computed from private fields
- Example:
get area => pi * _radius * _radius;
-
Change Notification
- Definition: Trigger actions on change
- Example:
set value(int v) { _value = v; _notifyListeners(); }
How to Use
- Data Hiding: Keep fields private
- Validation: In setters
- Computed Values: Via getters
- Documentation: Explain public API
How It Works
- Privacy:
_
prefix limits scope - Access: Getters/setters control visibility
- Maintenance: Internal changes don’t break API
- Tooling: Analyzer enforces access
Example:
class User {
String _id;
String _name;
User(this._id, this._name);
// Public API
String get id => _id;
String get name => _name;
set name(String value) {
if (value.isEmpty) throw ArgumentError();
_name = value;
}
}
Conclusion
Combining private variables with getters and setters provides robust encapsulation, allowing classes to maintain strict control over their internal state while exposing a clean, validated public API. This pattern is fundamental to object-oriented design in Dart.