Mixin vs Interface
Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 55 of 110.
You've seen how mixins compare to inheritance. Now let's compare mixins to interfaces, since both allow you to work with multiple types. The key difference is what they provide: interfaces define a contract, while mixins provide implementation.
When you implement an interface, you promise to provide certain methods, but you write all the code yourself. When you use a mixin, you get the actual code for free.
// Interface approach - you must implement everything
abstract class Printable {
void printInfo();
}
class Report implements Printable {
@override
void printInfo() {
print('Printing report...'); // You write this
}
}
// Mixin approach - implementation included
mixin Printable {
void printInfo() {
print('Printing...'); // Already written for you
}
}
class Report with Printable {} // Gets printInfo() automaticallySo when should you use each? Use an interface when different classes need the same method signatures but different implementations. Use a mixin when classes should share the exact same behavior.
| Feature | Interface | Mixin |
|---|---|---|
| Provides | Contract only | Contract + code |
| Implementation | You write it | Included |
| Keyword | implements | with |
| Best for | Different behaviors, same API | Shared behavior |
You can even combine both approaches - use interfaces to define what a class can do, and mixins to provide common implementations where appropriate. In Dart, when combining both, always put with before implements:
class MyClass with SomeMixin implements SomeInterface {
// with comes before implements
}Challenge
EasyLet's build a notification system that demonstrates when to use interfaces versus mixins. You'll create an interface for notifications that require different implementations, and a mixin for shared logging behavior that should be identical across all notification types.
You'll organize your code into three files:
notifiable.dart: Define an abstract classNotifiablethat acts as an interface. It should declare two abstract methods:send(String message)andgetChannel()that returns aString. Different notification types will implement these methods differently based on their specific channel.logging.dart: Create aLoggingmixin that provides shared behavior all notifications should have. Include a methodlogSent(String channel, String message)that prints[LOG] Sent via [channel]: [message]and a methodlogTimestamp()that prints[LOG] Timestamp recorded. This behavior is identical for all notification types, making it perfect for a mixin.main.dart: Import both files and create two notification classes that combine the interface with the mixin:- An
EmailNotificationclass that uses theLoggingmixin and implementsNotifiable. ItsgetChannel()should return'Email', and itssend()method should printSending email: [message], then calllogSent()with the channel and message, then calllogTimestamp() - An
SMSNotificationclass that uses theLoggingmixin and implementsNotifiable. ItsgetChannel()should return'SMS', and itssend()method should printSending SMS: [message], then calllogSent()with the channel and message, then calllogTimestamp()
EmailNotificationand callsend('Hello World'), print an empty line, create anSMSNotificationand callsend('Quick update')- An
Notice how the interface forces each class to write its own send() and getChannel() implementations (different behavior), while the mixin provides the logging methods that work identically for both (shared behavior).
Expected output:
Sending email: Hello World
[LOG] Sent via Email: Hello World
[LOG] Timestamp recorded
Sending SMS: Quick update
[LOG] Sent via SMS: Quick update
[LOG] Timestamp recordedCheat sheet
Interfaces define a contract (method signatures), while mixins provide implementation (actual code).
When you implement an interface, you must write all the code yourself:
abstract class Printable {
void printInfo();
}
class Report implements Printable {
@override
void printInfo() {
print('Printing report...'); // You write this
}
}When you use a mixin, you get the implementation for free:
mixin Printable {
void printInfo() {
print('Printing...'); // Already written for you
}
}
class Report with Printable {} // Gets printInfo() automaticallyWhen to use each:
- Use an interface when different classes need the same method signatures but different implementations
- Use a mixin when classes should share the exact same behavior
| Feature | Interface | Mixin |
|---|---|---|
| Provides | Contract only | Contract + code |
| Implementation | You write it | Included |
| Keyword | implements | with |
| Best for | Different behaviors, same API | Shared behavior |
You can combine both approaches. When combining, always put with before implements:
class MyClass with SomeMixin implements SomeInterface {
// with comes before implements
}Try it yourself
import 'notifiable.dart';
import 'logging.dart';
// TODO: Create EmailNotification class that:
// - uses the Logging mixin (with)
// - implements Notifiable (implements)
// - getChannel() returns 'Email'
// - send() prints 'Sending email: [message]', then calls logSent(), then logTimestamp()
// TODO: Create SMSNotification class that:
// - uses the Logging mixin (with)
// - implements Notifiable (implements)
// - getChannel() returns 'SMS'
// - send() prints 'Sending SMS: [message]', then calls logSent(), then logTimestamp()
void main() {
// TODO: Create an EmailNotification and call send('Hello World')
// TODO: Print an empty line
// TODO: Create an SMSNotification and call send('Quick update')
}
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