DDD describes that repositories should be used to store and manage aggregates. This is one of those patterns that once I learned it, I knew I’d never stop using it. It is a pattern that relies on hiding the implementation of the storage/database solution behind an interface. This allows us to define a set of methods that has to be present, and if they are present it is qualified to be used as a repository.

The advantage of this design pattern is that it allows us to exchange the solution without breaking anything. We can have in-memory storage used during the development phase, and then later switch that out to MongoDB storage for production. Not only does it help with changing the underlying technology used without breaking anything that leverages the repository, but it is also very useful in testing. You can easily implement a new repository simply for unit tests etc.

We will begin by creating a file called repository.go inside the domain/customer package. In that file, we will define the functions needed for a repository. We will want to Get, Add and Update customers. We will not be deleting any customers, once a customer in this tavern you are always a customer. We will also implement some generic errors in the customer package that the different repository implementations can use.

repository.go — Defining the rules around a repository for storing customers

Next up we need to implement an actual business logic that fulfills the interface, we will start with memory storage. At the end of the article, we will look at how we can change that to a MongoDB solution, without breaking anything else.

I like keeping each implementation inside its directory, just to make it easier for a fresh developer in the team to find the correct code location. Let’s create a folder called memory to indicate that the repository is using memory as storage.

Another solution can be having the memory.go in the customer package, but I find it getting cluttered fast in bigger systems

mkdir memory
touch memory/memory.go

Let’s first set up the correct structure in the memory file, we want to create a struct that has methods to fulfill the CustomerRepository, and let’s not forget the factory to create a new repository.

The structure needed for a new CustomerRepository to be added

We need to add a way of retrieving information from the Customer aggregate, such as an ID from the root entity. So we should update the aggregate with a little function for grabbing the ID, and a function…

Continue reading: https://towardsdatascience.com/how-to-implement-domain-driven-design-ddd-in-golang-2e2139beb09d?source=rss—-7f60cf5620c9—4

Source: towardsdatascience.com