Menu
CoddyTech

Properties and Privacy

Lesson 29 of 48 in Coddy's Dart for PHP Developers course.

PHP private properties are restricted to their declaring class; an underscore alone does not enforce privacy. Dart underscore names are instead private to the library, so other declarations in that library can access them. Dart getters allow property syntax while computing a value. In the PHP 8.3 example a public method exposes the check over a private property; later PHP property-hook syntax is not needed. Separate Dart files normally create library boundaries. A read-only public view can still reflect state changed by methods.

Complete PHP program:

<?php
class Token {
    public function __construct(private string $text) {}
    public function valid(): bool { return $this->text !== ''; }
}
echo json_encode((new Token('abc'))->valid()), "\n";

Complete Dart program:

class Token{final String _text;Token(this._text);bool get valid=>_text.isNotEmpty;}
void main(){print(Token('abc').valid);}
challenge icon

Challenge

Easy

Implement Wallet(int initial) with private balance, public read-only getter balance, and bool withdraw(int amount). Reject negative amounts and amounts above balance without changing state; otherwise subtract and return true. Initial balance is nonnegative. Input is initial balance followed by amounts, all between -100 and 100. Output comma-separated accepted:balance results, or empty for no withdrawals.

Do not print from editable files. The supplied exercise.dart parses input and returns output; the locked driver independently probes the public APIs and prints the result with one newline.

Your code goes in Wallet.dart, exercise.dart. main.dart holds the supplied input/output code and cannot be edited.

Try it yourself

import 'dart:io';
import 'dart:convert';
import 'exercise.dart';
import 'Wallet.dart';
void check(bool condition){if(!condition)throw StateError('Public API contract failed');}
Future<void> main() async {
final raw=await stdin.transform(utf8.decoder).join();
final input=raw.replaceFirst(RegExp(r'\r?\n$'),'');
final w=Wallet(9);check(w.withdraw(4) && w.balance==5);check(!w.withdraw(-1) && !w.withdraw(6) && w.balance==5);check(Wallet(2).balance==2);
stdout.writeln(solve(input));
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Dart for PHP Developers

Practice on your own: Online Dart compiler