Dart
SOLID
Learn SOLID principles.
SOLID
SOLID is a set of five design principles: Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion.
Single Responsibility: each class does one thing. Report carries data, ReportPrinter produces output. A change affects one class.
Dependency Inversion: high-level modules depend on interfaces, not low-level modules. OrderService depends on the PaymentService interface, not the concrete StripePayment.
The Open/Closed principle
Open/Closed: classes are open for extension, closed for modification. New behavior is added via a new subclass or interface implementation, without changing existing code.
Example: adding CryptoPayment to the PaymentService interface does not change OrderService. The class stays closed; the system stays open.
This principle uses inheritance and polymorphism. You define interfaces instead of concrete classes; new behavior comes with a new class.
Exercise Define Report and ReportPrinter
Define a Report class with final String title; final String content; Report(this.title, this.content);. Define a ReportPrinter class with String format(Report r) => '${r.title}: ${r.content}';. In main create final report = Report('Aylık', 'Satışlar arttı');; create final printer = ReportPrinter(); and add print(printer.format(report));.
Show example solution
class Report {
final String title;
final String content;
Report(this.title, this.content);
}
class ReportPrinter {
String format(Report r) => '${r.title}: ${r.content}';
}
void main() {
final report = Report('Aylık', 'Satışlar arttı');
final printer = ReportPrinter();
print(printer.format(report));
}
Test yourself
-
Liskov substitution
class SavingsAccount ____ Account { }
Show answer
class SavingsAccount extends Account { }
-
Match the SOLID principles
- S
- Single responsibility
- O
- Open/closed
- L
- Liskov substitution
- I
- Interface segregation
- D
- Dependency inversion
-
What does the Single Responsibility Principle say?
- Each class should implement an interface
- Each class should be extensible
- Each class should be closed
- Each class should do one thing
Show answer
Each class should do one thing — each class should have a single responsibility.
Next lesson: Summary - Architecture