Properties and Privacy
Lesson 29 of 48 in Coddy's Dart for C# Developers course.
C# properties and Dart getters both offer property syntax for computations. C# private restricts a member to its type; a Dart underscore is private to the whole library. Imported libraries do not gain access.
A getter can expose computed or read-only state. Underscore names are private to the library, not just the class. Separate library files keep storage inaccessible to callers while public methods enforce invariants.
Complete C# program:
using System;
using System.Collections.Generic;
using System.Linq;
class Program {
class Token{private readonly string text;public Token(string text){this.text=text;}public bool Valid{get{return text.Length>0;}}}
static void Main(){Console.WriteLine(new Token("abc").Valid);}
}
Complete Dart program:
class Token{final String _text;Token(this._text);bool get valid=>_text.isNotEmpty;}
void main(){print(Token('abc').valid);}Challenge
EasyImplement 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));
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Dart for C# Developers
1First Dart Programs
Run Dart FilesOutput and CommentsImports and LibrariesBindings and TypesNumeric OperationsRecap: Parcel Invoice4Collection Pipelines
Iterables and LazinessMaps and Missing KeysSets and MembershipClosures and CallbacksSorting and ComparatorsRecap: Word Inventory3Functions and Values
Functions and ReturnsNamed ParametersNull SafetyStrings and UnicodeLists and MutationRecap: Record Readings6Objects and State
Classes and InstancesConstructors and FactoriesProperties and PrivacyIdentity and CopiesComposition Across FilesRecap: Bounded Counter9Parcel Depot Project
Depot: Valid ItemsDepot: Register StockPractice on your own: Online Dart compiler