CodeBlanks Logo Icon CodeBlanks

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.

Practice 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));.

Starter code

main.dart
void main() {
  // define a Report class (title, content fields)
  // define a ReportPrinter class (format method)
  // create a report and a printer; print via format
}

Sample solution

main.dart
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));
}

Expected output

Aylık: Satışlar arttı

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Liskov substitution

Question
class SavingsAccount ____ Account { }
Answer
class SavingsAccount extends Account { }

Explanation: a subclass extends and substitutes for its parent (Liskov).

2 Match the SOLID principles

Term Meaning
S Single responsibility
O Open/closed
L Liskov substitution
I Interface segregation
D Dependency inversion

3 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 Correct answer

Explanation: each class should have a single responsibility.

All lessons in Expert