We have briefly mentioned the importance of design patterns in the first article of the series. We now elaborate a bit more and we will focus mainly on the Generic Repository pattern combined with the Unit of Work which are now used as standards for our new development at Synetec.
Let’s start by talking about the Generic Repository pattern. As already mentioned in a previous article it is very important to adopt an architecture that will allow the development team to grow in order to be able to bring new features to your application but also to make the collaboration between engineers as easy as possible. We will assume in this article that you are familiar with the basic N-Tier architecture.
The Generic Repository pattern can be seen as a mediator between the data tier and the business tier and like any pattern it has its pros and cons. For the positive:
- The pattern provides an abstraction of the data logic
- When implemented properly it facilitates the unit testing. It is easy to mock your repositories. Some great libraries save you a lot of time as you don’t need to write any stubs which can be timely
- No repetition needed as the basic operations on your entities are taken care of by the pattern
As there is no such thing as a perfect solution in Software Development the Generic Repository pattern also comes with its negatives:
- As we add a new layer of abstraction it means that we bring a certain level of complexity to our code base which can be more difficult to understand for junior developers
- In some systems we might encounter some performance issues
Software is more and more complex nowadays and even in small applications we would find different patterns associated together. If this is not the case it is probably a sign of bad architecture. The Generic Repository pattern matches very well with the Unit of Work. The principle of the latter is to keep track of everything during a business transaction to update the database only at the end. Let’s say for example that during a transaction you need to change the data of three different entities. Everything goes well for the first two but you encounter a problem for the third. By using a Unit of Work you are sure that your data won’t change unless the modification of the three entities is a success. To summarise, the beauty of using the Unit of Work pattern is that you can do the manipulation you want on your data and persist with the changes at the end in one go.
These patterns are source of debates within the community on whether they are good or bad. As already mentioned there is no perfect solution and rather than debating on whether a pattern is good or bad ask yourself if it does the job for what you want to achieve.
Written by Tarik Miri