A class groups values and behavior around an idea in your domain. Start from what the application needs to represent, rather than creating a class for every noun you can imagine.
A practice session model
class PracticeSession {
const PracticeSession({required this.topic, required this.minutes});
final String topic;
final int minutes;
bool get isShort => minutes <= 15;
String describe() => '$topic · $minutes minutes';
}
void main() {
const session = PracticeSession(topic: 'Layout', minutes: 12);
print(session.describe());
print('Short session: ${session.isShort}');
}Derive what you can
isShort depends on minutes. A getter makes that relationship explicit and avoids storing another value that could disagree with the duration.
Immutability simplifies change
Final fields prevent reassignment after construction. To represent an updated session, create a new instance. This can make state transitions easier to compare and reason about.
For nested objects, remember that final references do not automatically make every referenced object immutable.
Keep validation at a clear boundary
Decide whether a negative duration should be rejected during parsing, construction or a specific operation. Validate external input before treating it as a trusted model.
Separate stored values from derived facts
The session stores topic and minutes. isShort is calculated from minutes, so it cannot become inconsistent with a second independently updated boolean. describe similarly derives a label from current model data.
Final fields keep this object’s bindings stable after construction. If a future model contains a mutable list, that referenced list still needs its own immutability policy. A constructor marked const is not permission to ignore nested state.
Use a new instance to represent an immutable update, and validate external payloads before creating a trusted model. The JSON boundary lesson applies these language mechanics to remote app data.
Try it yourself
Add a completed field. Write a method that returns a completed copy instead of modifying the existing instance. Print both objects’ values to verify the original remains unchanged.