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

  1. 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;
      }
  2. Validation

    • Definition: Check input values
    • Example:
      set age(int value) {
        if (value < 0) throw ArgumentError();
        _age = value;
      }
  3. Derived Properties

    • Definition: Computed on access
    • Example:
      get fullName => '$firstName $lastName';
  4. Read-only

    • Definition: Getter without setter
    • Example:
      get area => length * width;
  5. 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

  1. Invocation: Called on access
  2. Syntax: Looks like field access
  3. Performance: Small overhead
  4. 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.