Design Patterns – How Aggregate Root and Repository Pattern Solve DRY in Database Operations

aggregatecruddesign-patternsdryrepository

If I have ten classes, and they all need CRUD operations, how does an Aggregate Root and the Repository Pattern solve me having to write lots of boilerplate code (the DRY)?

Take the example of a School and I have a Student, Teacher, Subject, Schedule, Room, …, etc.

If I did nothing, I'd have a service or class somewhere that had an individual Create for each object and have that for each class. That's five or more repetitions, typing, of almost the same action. The columns will be different but not much else.

My understanding of the Aggregate Root (AR) is to take that AR concept and group "behaviors" based upon a Use case. So, I end up with less, I think, models or services to do CRUD.

I have read lots of questions on SO, SE, and Blog. Way too many to reference here. I have also read much on the Repository Pattern. Many of the Repository Pattern examples end up with a Repository for each Model. That's the same boat I was in before (and there were SO questions that confirmed that.)

So I am confused on what I am accomplishing here. It sounds like I am simply reducing the number of Commands that need to be boilerplated and that there is not "magic" way to create a generic do everything CRUD and all the other database specialties for object and behavior X.

Is this correct?

Best Answer

They don't.

Those concepts reduce or centralize the number of calls your business code needs to load any data objects by calling CRUD code directly, but actually the CRUD code to load or update or save the objects still has to be somewhere, since it is used, at least, from inside the repository.

You reduce the need of writing such boilerplate by using code generation techniques, an ORM or some kind of Micro ORM which generates the CRUD code either ahead-of-time or just-in-time. But this is mostly orthogonal to the Repository Pattern or the Aggregate Root concept.

Related Topic