DartBasic 2 min read

Dart getters, setters and privacy: protect an account balance

Expose readable state while keeping mutation rules inside the owning object.

On this page

A model can allow reading a value without allowing arbitrary assignment. Use a getter for a derived or controlled property, and use a named method when a mutation represents a business operation. A private field helps communicate ownership within the library.

Worked example

Language requirement: Dart 3.0 or later. This complete example uses browser-supported libraries.

main.dart
class Wallet {
  int _balancePaise = 0;
  int get balancePaise => _balancePaise;

  void deposit(int amount) {
    if (amount <= 0) throw ArgumentError('Deposit must be positive.');
    _balancePaise += amount;
  }

  bool trySpend(int amount) {
    if (amount <= 0) throw ArgumentError('Spend must be positive.');
    if (amount > _balancePaise) return false;
    _balancePaise -= amount;
    return true;
  }
}

void main() {
  final wallet = Wallet()..deposit(10000);
  print(wallet.trySpend(3500));
  print(wallet.balancePaise);
}

Follow the data and control flow

The object owns the balance and validates each operation before changing it. trySpend reports an expected insufficient-funds outcome with a boolean while invalid amounts are programming/input-contract failures. The displayed balance becomes 6500 paise after the successful spend.

A getter should be inexpensive and unsurprising. Use a method for work that performs I/O or has a meaningful side effect. A setter can validate a replacement value, but this wallet deliberately exposes operations rather than a public balance setter.

A mistake to avoid

Underscore privacy is per Dart library; it is not per object or per file in a library with parts. Do not treat it as authorization. This in-memory teaching model also does not implement durable accounting or transaction isolation, which a real financial backend would need.

Practice and verification

Try spending more than the balance and confirm the balance remains unchanged. Add a receipt result for a successful operation. Explain why returning the mutable internal transaction list directly would weaken ownership.

How this topic connects

Apply it next

Lesson progressMark complete after checking the example and exercise.

Find your next idea

Search lessons, code examples and projects.

Type a few words to start exploring.