Dart: Project Design and Development — DataPipeline CLI Tool
Last updated: 2026-08-26
A true engineer doesn't just write code; they design architectures that allow code to grow. — Bob
1. What You Will Learn
- Project architecture design: Layered / Module division / Dependency injection
- CLI argument parsing (args package) and subcommand design
- Data source abstraction (Sealed class) + multi-format parsers
- Asynchronous pipeline design (Stream + Isolate parallel processing)
- Charlie's code review: Code quality and Pattern Matching in practice
2. A Developer's Real Story
(1) Pain Point: The Growing Pains from Scripts to a Tool
Bob initially wrote several independent Dart scripts to process e-commerce data: parse_csv.dart, calc_stats.dart, gen_report.dart. As requirements grew, more and more copy-pasting occurred between scripts. Changing a single field name required modifying 5 files. Alice asked, "Can we add a JSON data source?" Bob realized all parsing logic was tightly coupled with CSV and was difficult to modify.
(2) The Redesign Solution
Bob decided to design DataPipeline from scratch, adopting a layered architecture, abstracting data sources with Sealed classes, and using Stream pipelines for asynchronous processing. Charlie performed the code review to ensure quality.
graph TD
subgraph Architecture Layers
A[CLI Layer<br/>args Parsing]
B[Service Layer<br/>Pipeline Scheduling]
C[Data Layer<br/>Source + Parser]
D[Core Layer<br/>Models + Utils]
end
A --> B
B --> C
C --> D
B --> E[Isolate Pool]
B --> F[Stream Pipeline]
C --> G["Sealed DataSource"]
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
(3) Benefits
- Adding a new JSON data source only requires adding a subclass, with zero modifications to existing code
- Stream pipelines process millions of data records one by one, keeping memory usage under control
- Isolate parallel processing makes full use of a 4-core CPU
- CLI subcommands allow users to invoke analysis/export/validation as needed
3. Project Architecture Design
(1) Layered Architecture
| Layer | Directory | Responsibility | Dependencies |
|---|---|---|---|
| CLI Layer | bin/ |
Argument parsing, command routing | Service Layer |
| Service Layer | lib/src/services/ |
Pipeline scheduling, Isolate management | Data + Core Layer |
| Data Layer | lib/src/data/ |
Data source abstraction, parsers | Core Layer |
| Core Layer | lib/src/core/ |
Models, utilities, constants | No external dependencies |
▶ Example
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
: Project Directory Structure
data_pipeline/
bin/
data_pipeline.dart # CLI entry point
lib/
src/
core/
models/
order.dart
product.dart
customer.dart
analysis_result.dart
utils/
formatters.dart
validators.dart
constants.dart
data/
sources/
data_source.dart # Sealed class
csv_source.dart
json_source.dart
api_source.dart
parsers/
order_parser.dart
product_parser.dart
services/
pipeline.dart
analyzer.dart
isolate_pool.dart
report_generator.dart
data_pipeline.dart # Barrel export
test/
core/
models_test.dart
utils_test.dart
data/
parsers_test.dart
services/
pipeline_test.dart
analyzer_test.dart
pubspec.yaml
```text
```text
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
4. CLI Argument Parsing and Subcommands
(1) args Package Subcommand Design
▶ Example
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
: CLI Entry Point and Subcommands
import 'package:args/args.dart';
import 'package:args/command_runner.dart';
// Sub-command: analyze
class AnalyzeCommand extends Command {
@override
final name = 'analyze';
@override
final description = 'Analyze order data and generate statistics';
AnalyzeCommand() {
argParser
..addOption('source', abbr: 's', defaultsTo: 'csv', allowed: ['csv', 'json', 'api'])
..addOption('input', abbr: 'i', mandatory: true)
..addOption('output', abbr: 'o', defaultsTo: 'stdout')
..addFlag('parallel', abbr: 'p', defaultsTo: false)
..addOption('isolate-count', defaultsTo: '4');
}
@override
Future``<void>`` run() async {
final source = argResults!['source'] as String;
final input = argResults!['input'] as String;
final output = argResults!['output'] as String;
final parallel = argResults!['parallel'] as bool;
final isolateCount = int.parse(argResults!['isolate-count'] as String);
print('Source: $source | Input: $input | Parallel: $parallel');
}
}
// Sub-command: export
class ExportCommand extends Command {
@override
final name = 'export';
@override
final description = 'Export analysis results to file';
ExportCommand() {
argParser
..addOption('format', defaultsTo: 'json', allowed: ['json', 'csv', 'markdown'])
..addOption('input', abbr: 'i', mandatory: true)
..addOption('output', abbr: 'o', mandatory: true);
}
@override
Future``<void>`` run() async {
final format = argResults!['format'] as String;
final input = argResults!['input'] as String;
final output = argResults!['output'] as String;
print('Export: $format | $input -> $output');
}
}
void main(List``<String>`` args) async {
final runner = CommandRunner('data_pipeline', 'DataPipeline - E-commerce data analytics CLI')
..addCommand(AnalyzeCommand())
..addCommand(ExportCommand());
try {
await runner.run(args);
} on UsageException catch (e) {
print(e);
}
}
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
| Subcommand | Function | Key Parameters |
|---|---|---|
analyze |
Data analysis and statistics | --source, --input, --parallel |
export |
Export report | --format, --input, --output |
validate |
Data validation | --input, --strict |
5. Data Source Abstraction — Sealed Class
▶ Example
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
: Sealed DataSource
sealed class DataSource {
const DataSource();
String get displayName;
Stream``<String>`` readLines();
}
class CsvSource extends DataSource {
final String path;
final String delimiter;
const CsvSource({required this.path, this.delimiter = ','});
@override
String get displayName => 'CSV: $path';
@override
Stream``<String>`` readLines() => File(path).openRead().transform(utf8.decoder).transform(const LineSplitter());
}
class JsonSource extends DataSource {
final String path;
const JsonSource({required this.path});
@override
String get displayName => 'JSON: $path';
@override
Stream``<String>`` readLines() async* {
final content = await File(path).readAsString();
final jsonList = jsonDecode(content) as List;
for (final item in jsonList) {
yield jsonEncode(item);
}
}
}
class ApiSource extends DataSource {
final String endpoint;
final Map<String, String> headers;
const ApiSource({required this.endpoint, this.headers = const {}});
@override
String get displayName => 'API: $endpoint';
@override
Stream``<String>`` readLines() async* {
final client = Client();
final response = await client.get(Uri.parse(endpoint), headers: headers);
final jsonList = jsonDecode(response.body) as List;
for (final item in jsonList) {
yield jsonEncode(item);
}
client.close();
}
}
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
▶ Example
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
: Pattern Matching to Consume DataSource
DataSource createSource(String type, String input) => switch (type) {
'csv' => CsvSource(path: input),
'json' => JsonSource(path: input),
'api' => ApiSource(endpoint: input),
_ => throw ArgumentError('Unknown source type: $type'),
};
String sourceIcon(DataSource source) => switch (source) {
CsvSource() => '📄',
JsonSource() => '📋',
ApiSource() => '🌐',
};
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
| Pattern | Purpose | Advantage |
|---|---|---|
| Sealed class | Data source types | Exhaustive switch compile-time guarantee |
| Pattern Matching | Consuming data sources | No if-else chains |
| Factory function | Creating data sources | Unified entry point |
6. Multi-Format Parsers
▶ Example
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
: Order Parser
abstract class OrderParser {
const OrderParser();
Order parse(String raw);
List``<Order>`` parseBatch(List``<String>`` raws) => raws.map(parse).toList();
}
class CsvOrderParser extends OrderParser {
final String delimiter;
const CsvOrderParser({this.delimiter = ','});
@override
Order parse(String raw) {
final parts = raw.split(delimiter);
if (parts.length < 4) {
throw FormatException('Invalid CSV row: $raw');
}
return Order(
id: parts[0].trim(),
amount: double.parse(parts[1].trim()),
status: parts[2].trim(),
category: parts[3].trim(),
region: parts.length > 4 ? parts[4].trim() : 'US',
);
}
}
class JsonOrderParser extends OrderParser {
const JsonOrderParser();
@override
Order parse(String raw) {
final json = jsonDecode(raw) as Map<String, dynamic>;
return Order(
id: json['id'] as String,
amount: (json['amount'] as num).toDouble(),
status: json['status'] as String,
category: json['category'] as String,
region: (json['region'] as String?) ?? 'US',
);
}
}
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
7. Stream Asynchronous Pipeline
▶ Example
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
: Pipeline Stream Processing
import 'dart:async';
import 'dart:convert';
import 'dart:io';
class Pipeline {
final DataSource _source;
final OrderParser _parser;
final int _chunkSize;
Pipeline({
required DataSource source,
required OrderParser parser,
int chunkSize = 1000,
}) : _source = source,
_parser = parser,
_chunkSize = chunkSize;
Future``<AnalysisResult>`` execute() async {
final orders = ``<Order>``[];
var processed = 0;
var skipped = 0;
await for (final line in _source.readLines()) {
try {
final order = _parser.parse(line);
orders.add(order);
processed++;
} on FormatException {
skipped++;
}
if (processed % _chunkSize == 0) {
stdout.writeln('Progress: $processed orders processed, $skipped skipped');
}
}
stdout.writeln('Total: $processed processed, $skipped skipped');
final analyzer = OrderAnalyzer();
return analyzer.analyze(orders);
}
Stream``<Order>`` streamOrders() async* {
await for (final line in _source.readLines()) {
try {
yield _parser.parse(line);
} on FormatException {
continue;
}
}
}
Stream``<AnalysisResult>`` streamByCategory() {
final controller = StreamController``<AnalysisResult>``();
streamOrders().fold<Map<String, List``<Order>``>>(
{},
(groups, order) {
groups.update(order.category, (v) => v..add(order), ifAbsent: () => [order]);
return groups;
},
).then((groups) {
final analyzer = OrderAnalyzer();
for (final entry in groups.entries) {
controller.add(analyzer.analyze(entry.value));
}
controller.close();
});
return controller.stream;
}
}
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
8. Isolate Parallel Processing
▶ Example
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
: Isolate Pool
import 'dart:isolate';
class IsolatePool {
final int _poolSize;
final List``<Isolate>`` _isolates = [];
final List``<SendPort>`` _sendPorts = [];
IsolatePool({int poolSize = 4}) : _poolSize = poolSize;
Future``<void>`` initialize() async {
for (var i = 0; i < _poolSize; i++) {
final receivePort = ReceivePort();
final isolate = await Isolate.spawn(
_isolateEntryPoint,
receivePort.sendPort,
);
final sendPort = await receivePort.first as SendPort;
_isolates.add(isolate);
_sendPorts.add(sendPort);
}
}
static void _isolateEntryPoint(SendPort mainSendPort) {
final receivePort = ReceivePort();
mainSendPort.send(receivePort.sendPort);
receivePort.listen((message) {
if (message is _IsolateTask) {
final result = _processChunk(message.orders, message.taxRate);
message.responsePort.send(result);
}
});
}
static AnalysisResult _processChunk(List<Map<String, dynamic>> rawOrders, double taxRate) {
final orders = rawOrders.map((o) => Order(
id: o['id'] as String,
amount: (o['amount'] as num).toDouble(),
status: o['status'] as String,
category: o['category'] as String,
region: (o['region'] as String?) ?? 'US',
)).toList();
final analyzer = OrderAnalyzer(taxRate: taxRate);
return analyzer.analyze(orders);
}
Future<List``<AnalysisResult>``> processInParallel(
List<Map<String, dynamic>> allOrders,
double taxRate,
) async {
final chunkSize = (allOrders.length / _poolSize).ceil();
final results = ``<AnalysisResult>``[];
final completers = <Completer``<AnalysisResult>``>[];
for (var i = 0; i < _poolSize; i++) {
final start = i * chunkSize;
final end = (start + chunkSize).clamp(0, allOrders.length);
if (start >= allOrders.length) break;
final chunk = allOrders.sublist(start, end);
final completer = Completer``<AnalysisResult>``();
completers.add(completer);
_sendPorts[i].send(_IsolateTask(
orders: chunk,
taxRate: taxRate,
responsePort: completer.future as dynamic,
));
}
for (final completer in completers) {
results.add(await completer.future);
}
return results;
}
void dispose() {
for (final isolate in _isolates) {
isolate.kill(priority: Isolate.immediate);
}
}
}
class _IsolateTask {
final List<Map<String, dynamic>> orders;
final double taxRate;
final SendPort responsePort;
const _IsolateTask({
required this.orders,
required this.taxRate,
required this.responsePort,
});
}
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
| Parallel Model | Suitable Scenario | Advantage |
|---|---|---|
| Isolate.run | One-time computation | Simple API |
| Isolate.spawn | Long-running worker | Reusable |
| Isolate Pool | Even sharding | Full utilization of multiple cores |
| compute (Flutter) | No UI jank | Flutter-specific |
9. Dependency Injection
▶ Example
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
: Service Locator Pattern
class ServiceLocator {
static final _instances = <Type, dynamic>{};
static void register``<T>``(T instance) {
_instances[T] = instance;
}
static T get``<T>``() {
final instance = _instances[T];
if (instance == null) {
throw StateError('Service not registered: $T');
}
return instance as T;
}
static void reset() {
_instances.clear();
}
}
// Registration at startup
void setupServices({required String sourceType, required String inputPath}) {
final source = createSource(sourceType, inputPath);
ServiceLocator.register``<DataSource>``(source);
final parser = switch (source) {
CsvSource() => const CsvOrderParser() as OrderParser,
JsonSource() => const JsonOrderParser(),
ApiSource() => const JsonOrderParser(),
};
ServiceLocator.register``<OrderParser>``(parser);
ServiceLocator.register``<OrderAnalyzer>``(const OrderAnalyzer());
ServiceLocator.register``<Pipeline>``(Pipeline(source: source, parser: parser));
}
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
10. Complete Example: DataPipeline CLI Tool
// ============================================
// DataPipeline CLI Tool - Complete Implementation
// Bob's e-commerce data analytics tool
// ============================================
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'dart:isolate';
// ---- Core Models ----
class Order {
final String id;
final double amount;
final String status;
final String category;
final String region;
const Order({
required this.id,
required this.amount,
required this.status,
required this.category,
this.region = 'US',
});
double get tax => amount * _taxRate(region);
double get total => amount + tax;
static double _taxRate(String region) => switch (region) {
'US' => 0.08,
'EU' => 0.20,
'UK' => 0.15,
'JP' => 0.10,
_ => 0.10,
};
Map<String, dynamic> toJson() => {
'id': id,
'amount': amount,
'status': status,
'category': category,
'region': region,
};
}
class AnalysisResult {
final int totalOrders;
final int completedOrders;
final double revenue;
final double tax;
final double total;
final Map<String, double> revenueByCategory;
const AnalysisResult({
required this.totalOrders,
required this.completedOrders,
required this.revenue,
required this.tax,
required this.total,
required this.revenueByCategory,
});
double get averageOrderValue => completedOrders > 0 ? revenue / completedOrders : 0;
@override
String toString() => '''
=== DataPipeline Analytics ===
Orders: $completedOrders/$totalOrders completed
Revenue: \$${revenue.toStringAsFixed(2)} USD
Tax: \$${tax.toStringAsFixed(2)} USD
Total: \$${total.toStringAsFixed(2)} USD
Average: \$${averageOrderValue.toStringAsFixed(2)} USD
Categories: ${revenueByCategory.keys.join(', ')}
''';
}
// ---- Core Services ----
class OrderAnalyzer {
final double taxRate;
const OrderAnalyzer({this.taxRate = 0.08});
AnalysisResult analyze(List``<Order>`` orders) {
final completed = orders.where((o) => o.status == 'completed').toList();
final revenue = completed.fold``<double>``(0, (s, o) => s + o.amount);
final tax = completed.fold``<double>``(0, (s, o) => s + o.tax);
final total = revenue + tax;
final byCategory = <String, double>{};
for (final o in completed) {
byCategory.update(o.category, (v) => v + o.amount, ifAbsent: () => o.amount);
}
return AnalysisResult(
totalOrders: orders.length,
completedOrders: completed.length,
revenue: revenue,
tax: tax,
total: total,
revenueByCategory: byCategory,
);
}
}
// ---- Data Source (Sealed) ----
sealed class DataSource {
const DataSource();
String get displayName;
Stream``<String>`` readLines();
}
class CsvSource extends DataSource {
final String path;
const CsvSource({required this.path});
@override
String get displayName => 'CSV: $path';
@override
Stream``<String>`` readLines() =>
File(path).openRead().transform(utf8.decoder).transform(const LineSplitter());
}
class JsonSource extends DataSource {
final String path;
const JsonSource({required this.path});
@override
String get displayName => 'JSON: $path';
@override
Stream``<String>`` readLines() async* {
final content = await File(path).readAsString();
final list = jsonDecode(content) as List;
for (final item in list) {
yield jsonEncode(item);
}
}
}
// ---- Parser ----
abstract class OrderParser {
const OrderParser();
Order parse(String raw);
}
class CsvOrderParser extends OrderParser {
const CsvOrderParser();
@override
Order parse(String raw) {
final parts = raw.split(',');
if (parts.length < 4) throw FormatException('Invalid row: $raw');
return Order(
id: parts[0].trim(),
amount: double.parse(parts[1].trim()),
status: parts[2].trim(),
category: parts[3].trim(),
);
}
}
class JsonOrderParser extends OrderParser {
const JsonOrderParser();
@override
Order parse(String raw) {
final json = jsonDecode(raw) as Map<String, dynamic>;
return Order(
id: json['id'] as String,
amount: (json['amount'] as num).toDouble(),
status: json['status'] as String,
category: json['category'] as String,
);
}
}
// ---- Pipeline ----
class Pipeline {
final DataSource source;
final OrderParser parser;
const Pipeline({required this.source, required this.parser});
Future``<AnalysisResult>`` execute() async {
final orders = ``<Order>``[];
var count = 0;
await for (final line in source.readLines()) {
try {
orders.add(parser.parse(line));
count++;
if (count % 100000 == 0) {
stdout.writeln('Progress: ${(count / 1000).toStringAsFixed(0)}K orders');
}
} on FormatException {
continue;
}
}
stdout.writeln('Loaded: ${(count / 1000).toStringAsFixed(0)}K orders from ${source.displayName}');
return const OrderAnalyzer().analyze(orders);
}
}
// ---- Demo Data Generator ----
List``<String>`` generateDemoOrders(int count) {
final categories = ['Electronics', 'Clothing', 'Books', 'Home', 'Sports'];
final statuses = ['completed', 'completed', 'completed', 'pending', 'cancelled'];
final regions = ['US', 'EU', 'UK', 'JP'];
return List.generate(count, (i) {
final category = categories[i % categories.length];
final status = statuses[i % statuses.length];
final region = regions[i % regions.length];
final amount = (100 + (i * 37) % 5000).toDouble();
return 'ORD-${(i + 1).toString().padLeft(5, '0')},$amount,$status,$category,$region';
});
}
// ---- Main ----
void main() async {
print('=== DataPipeline CLI v1.0 ===\n');
final demoData = generateDemoOrders(1000);
final tempFile = File('${Directory.systemTemp.path}/demo_orders.csv');
await tempFile.writeAsString(demoData.join('\n'));
final source = CsvSource(path: tempFile.path);
final parser = const CsvOrderParser();
final pipeline = Pipeline(source: source, parser: parser);
print('Source: ${source.displayName}');
print('Processing...\n');
final result = await pipeline.execute();
print(result);
final sorted = result.revenueByCategory.entries.toList()
..sort((a, b) => b.value.compareTo(a.value));
print('Revenue by Category:');
for (final entry in sorted) {
print(' ${entry.key.padRight(12)}: \$${entry.value.toStringAsFixed(2)} USD');
}
await tempFile.delete();
print('\nDone. Temporary file cleaned up.');
}
> **Output:** Run locally in DartPad or using `dart run`. All examples in the Dart course are based on Dart 3.x / Flutter 3.x, and results may vary slightly depending on the SDK version.
11. Charlie's Code Review
(1) ▶ Review Points
| Dimension | Review Criteria | DataPipeline Checklist |
|---|---|---|
| Type Safety | No dynamic, exhaustive switch | Sealed DataSource + Pattern Matching |
| Testability | Core logic independent of I/O | OrderParser pure function, Pipeline accepts interface |
| Error Handling | Don't swallow exceptions, have fallbacks | FormatException skip + counting |
| Performance | Memory control, non-blocking async | Stream line-by-line + Isolate sharding |
| Extensibility | New features don't change old code | New DataSource subclass with zero modification |
Charlie: "Sealed class + Pattern Matching lets the compiler check for omissions, much safer than if-else. OrderParser is a pure function, so testing doesn't require mocking the file system."
❓ FAQ
Q: Why use Sealed class instead of enums for data sources? A: Enums cannot carry data (like path, endpoint). Sealed classes can have fields and methods while maintaining the compile-time guarantee of exhaustive switch.
Q: Should I choose Stream or Future in the Pipeline? A: Use Stream if data arrives record by record and needs real-time processing; use Future if you load everything at once and then process. For millions of records, Stream is recommended to avoid memory overflow.
Q: Can Isolate communication only pass primitive types? A: Data passed through SendPort must be serializable. Custom classes need to be converted to Maps or use jsonEncode/Decode. Dart 3's Records are also supported for passing.
Q: Which is better, the args package or the dcli package? A: args is an official package, suitable for standard subcommand patterns. dcli provides richer CLI tools (file operations, process management, etc.) but is unofficial. This tutorial uses args.
Q: Is a framework necessary for dependency injection? A: Not necessarily. For small projects, a Service Locator or constructor injection is sufficient. Frameworks like flutter_bloc, get_it are suitable for large projects. DataPipeline uses a simple ServiceLocator.
Q: How do I test the Pipeline's end-to-end flow? A: Use a temporary file (Directory.systemTemp) as the test data source and verify the values of each field in the output AnalysisResult. See the integration test example in Lesson L20.
📖 Summary
- Layered architecture makes responsibilities clear for CLI/Service/Data/Core layers, with unidirectional dependencies
- Sealed class abstracts data sources, Pattern Matching consumes them, compiler guarantees no omissions
- Stream pipeline processes millions of data records flowing one by one, keeping memory under control
- Isolate Pool parallel sharding fully utilizes multiple cores
- Dependency injection makes core logic testable and replaceable
📝 Exercises
- Basic (Difficulty ⭐): Add a
validatesubcommand to DataPipeline that accepts an--inputparameter, counts the number of incorrectly formatted lines in a CSV file, and reports it. - Advanced (Difficulty ⭐⭐): Implement
JsonSource+JsonOrderParser. Use a JSON array as input, run the Pipeline, and output the analysis results. Verify if the exhaustive switch of the Sealed class covers all subclasses. - Challenge (Difficulty ⭐⭐⭐): Implement
IsolatePool. Split 1000 demo data records into 4 shards, use 4 Isolates to analyze in parallel, and finally merge 4AnalysisResultobjects (summing revenue and order counts separately). Measure the time difference between parallel and sequential execution.