Repository Pattern, Revisited
--
Motivation
I first encountered the repository pattern in a Go backend codebase, where there are files/packages named “repo” and those packages are used to supply information from data sources. I was puzzled by such usage because until then, I have always known “repository” as a term related to “Git” and “GitHub”. With further research online, I then realized that the repository pattern is a popular abstraction layer between the business logic and the data sources.
A succinct description of the repository pattern by Edward Hieatt and Rob Mee ( P of EAA):
Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
This pattern is often discussed when talking about Domain Driven Design, which is
an approach to software development that centers the development on programming a domain model that has a rich understanding of the processes and rules of a domain. — Martin Fowler DomainDrivenDesign
In this article, I hope to consolidate some of the excellent resources that discuss the repository pattern in-depth and provide my examples and reflections on this pattern.
Uncovering the Repository Pattern
The idea of the repository pattern is to have a layer between a business domain and a data store. This can be done via an interface that defines data store handling logic, which the domain service logic can depend on.
Let’s discuss a simplified example in Go, in the context of a URL-shortener application.
1. Create a repository interface in the service layer
The example application provides a URL-shortening service, which essentially takes in any URL and returns a shortened version that redirects visitors to the original address.
Let’s assume that the URL-shortener service needs
- a way to create a mapping of the original URL and the shortened URL
- a way to query for the original URL for redirection
- anything else (for simplicity we will only focus on the two above, CR of CRUD)