Menu
CoddyTech

Composition Across Files

Lesson 31 of 48 in Coddy's Dart for JavaScript Developers course.

Composition puts references to collaborating objects in fields. Dart uses garbage-collected objects, not Rust-style ownership moves or C++ deterministic destructors. A final field prevents rebinding but does not make the collaborator immutable. JavaScript uses the same reference-based relationship. Keep dependency direction visible through imports and separate files in the tasks. The teaching example changes a shared speaker after giving it to a radio; the route task instead owns its collection of stop references.

Complete JavaScript program:

class Speaker{constructor(){this.tone='soft';}}class Radio{constructor(speaker){this.speaker=speaker;}play(){return this.speaker.tone;}}const s=new Speaker(),r=new Radio(s);s.tone='loud';console.log(r.play());

Complete Dart program:

class Speaker{String tone='soft';}
class Radio{final Speaker speaker;Radio(this.speaker);String play()=>speaker.tone;}
void main(){final s=Speaker();final r=Radio(s);s.tone='loud';print(r.play());}
challenge icon

Challenge

Easy

Implement Stop(String name,int minutes) with public final fields. Implement Route() with add(Stop stop), getter total, and names() returning stop names in insertion order as a fresh list. Input contains complete name/minutes pairs, at most 100, minutes 0 through 100. Output total|names with comma-separated names, using empty for no stops.

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 Stop.dart, Route.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 'Stop.dart';
import 'Route.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 r=Route();r.add(Stop('x',7));r.add(Stop('y',4));check(r.total==11 && r.names().join(',')=='x,y');r.names().clear();check(r.names().length==2 && Route().total==0);
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 JavaScript Developers

Practice on your own: Online Dart compiler