The _ Prefix Convention
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 31 of 110.
The underscore prefix _ is Dart's way of marking members as private. Unlike languages that use keywords like private, Dart relies on this naming convention to control visibility.
You can apply the underscore to both fields and methods:
class Counter {
int _count = 0; // Private field
void _increment() { // Private method
_count++;
}
void increase() { // Public method
_increment();
print('Count: $_count');
}
}The underscore works for any identifier - variables, methods, getters, setters, and even class names. A class named _Helper would be private to its library.
class Person {
String _name; // Private
int _age; // Private
Person(this._name, this._age);
String get name => _name; // Public getter
void _validateAge(int age) { } // Private method
}Inside the same class, you access private members normally. The restriction only applies to code outside the library. This convention makes it immediately clear when reading code which members are meant for internal use only - anything starting with _ is an implementation detail.
Challenge
EasyLet's build a score tracker for a game that demonstrates how the underscore prefix keeps internal implementation details hidden while exposing a clean public interface.
You'll organize your code into two files:
score_tracker.dart: Create aScoreTrackerclass that manages a player's score with proper encapsulation. The class should have:- A public
String playerName- everyone can see who's playing - A private
int _scoreinitialized to0- the raw score should be protected - A private
int _bonusMultiplierinitialized to1- this is an internal game mechanic - A constructor that takes the player name
- A public getter
scorethat returns the private_score - A private method
_applyBonus(int points)that returnspoints * _bonusMultiplier - A public method
addPoints(int points)that uses_applyBonusinternally to calculate the actual points added, updates_score, and printsAdded [calculated] points! - A public method
activateDoubleBonus()that sets_bonusMultiplierto2and printsDouble bonus activated! - A public method
displayStats()that shows the player's current status
- A public
main.dart: Import your score tracker and simulate a game session:- Create a
ScoreTrackerfor player'Alex' - Call
displayStats() - Add
10points - Add
25points - Activate the double bonus
- Add
15points (this should be doubled) - Call
displayStats() - Print
Final score: [score]using the public getter
- Create a
The displayStats() method should print in this format:
=== Player Stats ===
Player: [playerName]
Current Score: [_score]Notice how the private _applyBonus method and _bonusMultiplier field handle the bonus calculation internally. External code only sees the public methods and has no idea about the multiplier system - that's an implementation detail hidden behind the underscore convention.
Expected output:
=== Player Stats ===
Player: Alex
Current Score: 0
Added 10 points!
Added 25 points!
Double bonus activated!
Added 30 points!
=== Player Stats ===
Player: Alex
Current Score: 65
Final score: 65Cheat sheet
The underscore prefix _ marks members as private in Dart. This naming convention controls visibility without using keywords like private.
Apply the underscore to fields and methods:
class Counter {
int _count = 0; // Private field
void _increment() { // Private method
_count++;
}
void increase() { // Public method
_increment();
print('Count: $_count');
}
}The underscore works for any identifier - variables, methods, getters, setters, and class names:
class Person {
String _name; // Private
int _age; // Private
Person(this._name, this._age);
String get name => _name; // Public getter
void _validateAge(int age) { } // Private method
}Private members are accessible within the same class but restricted to code outside the library. Anything starting with _ is an implementation detail.
Try it yourself
import 'score_tracker.dart';
void main() {
// TODO: Create a ScoreTracker for player 'Alex'
// TODO: Call displayStats()
// TODO: Add 10 points
// TODO: Add 25 points
// TODO: Activate the double bonus
// TODO: Add 15 points (this should be doubled)
// TODO: Call displayStats()
// TODO: Print 'Final score: [score]' using the public getter
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Object Oriented Programming
1Fundamentals of OOP
External FilesLibraries & ImportsIntroduction to OOPClasses vs ObjectsThe this KeywordMethodsInstance VariablesConstructor BasicsRecap - Simple Calculator4Null Safety
Intro to Null SafetyNullable vs Non-NullableThe ? and ! OperatorsLate Keyword & Null SafetyNull-Aware OperatorsNull Safety in ClassesRecap - User Profile System7Abstract Classes & Interfaces
Abstract ClassesAbstract MethodsInterfaces in DartImplicit InterfacesImplementing vs ExtendingMultiple InterfacesRecap - Shape Calculator10Collections & Generics
List, Set, Map OverviewType-Safe CollectionsGeneric ClassesGeneric MethodsGeneric ConstraintsIterable & IteratorRecap - Generic Storage13Advanced OOP Concepts
Composition vs InheritanceExtension MethodsCallable ClassesSealed Classes (Dart 3)Records (Dart 3)Patterns & Matching (3.0)Enums with Methods16Project: Library Management
Project OverviewBook and User Classes2Constructors in Dart
Default ConstructorNamed ConstructorsInitializer ListsConstant ConstructorsFactory ConstructorsRedirecting ConstructorsRecap - Shape Builder5Encapsulation
Public vs Private MembersThe _ Prefix ConventionLibrary-Level PrivacyGetters & Setters DepthInformation HidingRecap - Student Records8Mixins
Introduction to MixinsCreating MixinsUsing Multiple Mixinson Keyword in MixinsMixin vs InheritanceMixin vs InterfaceRecap - Animal System11Special Methods
toString() OverridehashCode & == OverrideComparable Interfacecall() MethodnoSuchMethod OverrideRecap - Custom Collection14Design Patterns Part 1
Intro to Design PatternsSingleton PatternFactory PatternObserver PatternStrategy Pattern3Class Properties
Instance vs Static MembersFinal & Const FieldsLate VariablesStatic Methods & FieldsGetters and SettersRecap - Bank Account Manager6Inheritance
Basic InheritanceThe super KeywordMethod OverridingThe @override AnnotationThe final Class KeywordConstructors & InheritanceRecap - Employee Hierarchy9Polymorphism
Polymorphism BasicsPolymorphism via InterfacesRuntime Type CheckingThe is & as OperatorsCovariant KeywordRecap - Payment Processor