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

  1. Basic Encapsulation

    • Definition: Private fields with public accessors

    • Example:

      class Wallet {
        double _balance = 0;
      
        double get balance => _balance;
      }
  2. Validation

    • Definition: Protect invariants
    • Example:
      set balance(double value) {
        if (value < 0) throw ArgumentError();
        _balance = value;
      }
  3. Read-only Exposure

    • Definition: Public getter, private setter

    • Example:

      class Circle {
        final double _radius;
      
        double get radius => _radius;
      }
  4. Derived State

    • Definition: Computed from private fields
    • Example:
      get area => pi * _radius * _radius;
  5. 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

  1. Privacy: _ prefix limits scope
  2. Access: Getters/setters control visibility
  3. Maintenance: Internal changes don’t break API
  4. 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.