Menu
Coddy logo textTech

Repository Pattern

Part of the Object Oriented Programming section of Coddy's Dart journey — lesson 100 of 110.

The Repository pattern separates data access logic from business logic by creating an abstraction layer between your application and data sources. Instead of having your classes directly interact with databases, APIs, or files, they work with a repository that handles all data operations.

The pattern defines an interface for data operations, and concrete implementations handle the actual storage mechanism. This makes it easy to swap data sources without changing your business logic:

// Entity
class User {
  final int id;
  final String name;
  User(this.id, this.name);
}

// Repository interface
abstract class UserRepository {
  User? getById(int id);
  List<User> getAll();
  void save(User user);
  void delete(int id);
}

// In-memory implementation
class InMemoryUserRepository implements UserRepository {
  final Map<int, User> _users = {};

  @override
  User? getById(int id) => _users[id];

  @override
  List<User> getAll() => _users.values.toList();

  @override
  void save(User user) => _users[user.id] = user;

  @override
  void delete(int id) => _users.remove(id);
}

void main() {
  UserRepository repo = InMemoryUserRepository();
  
  repo.save(User(1, 'Alice'));
  repo.save(User(2, 'Bob'));
  
  print(repo.getById(1)?.name);  // Alice
  print(repo.getAll().length);    // 2
}

Your business logic depends only on the UserRepository interface. You could later create a DatabaseUserRepository or ApiUserRepository that implements the same interface, and swap implementations without modifying any code that uses the repository. This pattern is essential for testable, maintainable applications where data sources may change over time.

challenge icon

Challenge

Easy

Let's build a product inventory system using the Repository pattern! You'll create an abstraction layer that separates how products are stored from how they're used, making it easy to swap storage implementations without changing business logic.

You'll organize your code into two files:

  • product_repository.dart: This file contains your entity and repository classes. Start with a Product class that has final fields for id (int), name (String), and price (double). Then define an abstract class ProductRepository that declares the contract for data operations: getById(int id) returning a nullable Product, getAll() returning a list of products, save(Product product) to store a product, and delete(int id) to remove one. Finally, create an InMemoryProductRepository that implements this interface using a Map<int, Product> for storage.
  • main.dart: Import your repository file and demonstrate the Repository pattern in action. Create an InMemoryProductRepository but store it in a variable of type ProductRepository - this shows how your code depends on the interface, not the implementation. Save three products: Laptop (id: 1, price: 999.99), Mouse (id: 2, price: 29.99), and Keyboard (id: 3, price: 79.99). Then retrieve and print the product with id 2 in the format Found: [name] - $[price]. Delete the product with id 1. Finally, print the count of remaining products as Products in stock: [count].

The power of this pattern is that your main code only knows about the ProductRepository interface. You could later create a DatabaseProductRepository or ApiProductRepository and swap it in without changing any of the business logic!

Expected output:

Found: Mouse - $29.99
Products in stock: 2

Cheat sheet

The Repository pattern separates data access logic from business logic by creating an abstraction layer between your application and data sources.

Define an interface for data operations:

// Entity
class User {
  final int id;
  final String name;
  User(this.id, this.name);
}

// Repository interface
abstract class UserRepository {
  User? getById(int id);
  List<User> getAll();
  void save(User user);
  void delete(int id);
}

Create concrete implementations that handle the actual storage mechanism:

// In-memory implementation
class InMemoryUserRepository implements UserRepository {
  final Map<int, User> _users = {};

  @override
  User? getById(int id) => _users[id];

  @override
  List<User> getAll() => _users.values.toList();

  @override
  void save(User user) => _users[user.id] = user;

  @override
  void delete(int id) => _users.remove(id);
}

Use the repository through its interface:

void main() {
  UserRepository repo = InMemoryUserRepository();
  
  repo.save(User(1, 'Alice'));
  repo.save(User(2, 'Bob'));
  
  print(repo.getById(1)?.name);  // Alice
  print(repo.getAll().length);    // 2
}

Business logic depends only on the interface, allowing you to swap implementations (e.g., DatabaseUserRepository, ApiUserRepository) without modifying code that uses the repository.

Try it yourself

import 'product_repository.dart';

void main() {
  // Create repository - note the type is the interface, not the implementation
  // TODO: Create an InMemoryProductRepository and store it in a ProductRepository variable
  
  // TODO: Save three products:
  // - Laptop (id: 1, price: 999.99)
  // - Mouse (id: 2, price: 29.99)
  // - Keyboard (id: 3, price: 79.99)
  
  // TODO: Retrieve product with id 2 and print: "Found: [name] - $[price]"
  
  // TODO: Delete product with id 1
  
  // TODO: Print the count of remaining products: "Products in stock: [count]"
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Object Oriented Programming