Custom Getters and Setters
Custom Getters and Setters
About
- Explicit Control: Custom access logic
- Validation: Check values before setting
- Computation: Derived properties
- Syntax: Maintains field-like access
Main Topics
-
Basic Syntax
-
Definition: get/set keywords
-
Example:
class Temperature { double _celsius; double get fahrenheit => _celsius * 9/5 + 32; set fahrenheit(double f) => _celsius = (f - 32) * 5/9; }
-
-
Validation
- Definition: Check input values
- Example:
set age(int value) { if (value < 0) throw ArgumentError(); _age = value; }
-
Derived Properties
- Definition: Computed on access
- Example:
get fullName => '$firstName $lastName';
-
Read-only
- Definition: Getter without setter
- Example:
get area => length * width;
-
Logging
- Definition: Track access
- Example:
set value(int v) { print('Value changed to $v'); _value = v; }
How to Use
- Validation: Protect invariants
- Derived Data: Compute when needed
- Debugging: Add access logging
- Compatibility: Maintain API while changing implementation
How It Works
- Invocation: Called on access
- Syntax: Looks like field access
- Performance: Small overhead
- Optimization: JIT may inline
Example:
class BankAccount {
double _balance = 0;
double get balance => _balance;
set deposit(double amount) {
if (amount <= 0) throw ArgumentError();
_balance += amount;
}
set withdraw(double amount) {
if (amount > _balance) throw StateError();
_balance -= amount;
}
}
Conclusion
Custom getters and setters enable precise control over property access, allowing for validation, computed values, and other logic while maintaining clean field-like syntax. They’re essential for maintaining class invariants and creating robust APIs.