[ACCEPTED]-Active Records vs. Repository - pros and cons?-architectural-patterns

Accepted answer
Score: 11

It really depends on how complex your domain 12 logic is. For example if I was writing a 11 simple blog then active record will be fine, mostly 10 the application is saving and loading data. Its 9 simple and active record pattern is the 8 right tool for the job.

However if I was 7 writing software for a shipping company 6 in which there are many complex business 5 rules and processes then using the repository 4 pattern, along with other Domain Driven Design patterns will 3 provide at much more maintainable code in 2 the long run.

Using domain driven design 1 you would use the specification pattern to achieve your validation.

Score: 6

This article seems like a good and succinct 21 description of both: https://hashnode.com/post/which-design-pattern-do-you-prefer-active-record-or-repository-cilozoaa5016o6t53mhsdu6nu

One thing I would like 20 to add is it isn't just "active record 19 is good when your persistence needs are 18 simple and repository is good when your 17 persistence needs are complex". The 16 choice of pattern here has a lot more to 15 do with how you feel about the Law of Demeter. If 14 you want different parts of your architecture 13 to be completely separated so that someone 12 can understand one part without understanding 11 another then you want the Law of Demeter. That 10 said I think, especially early on in a project 9 when the spec is likely to change, it is 8 VERY dangerous to get too obsessive about 7 these sorts of abstraction. Don't second 6 guess your project's future maintainers, they 5 might be smart and they should be able to 4 think about more than one thing at a time 3 and if they can't then you might have larger 2 problems that cannot be prevented by using 1 the Repository pattern.

Score: 4

Both approaches has their pros and cons.

Pretend, you're 14 passing Active Record-styled object to somewhere 13 (deep inside BL). You can read it, you can 12 changed it, you can SAVE it. In this case, that 11 piece of BL is only coupled with you entity's 10 interface. With layered architecture you 9 then have to somehow pass repository to 8 that code. You'd either pass it explicitly 7 or use IoC-container - up to you.

The other 6 point is that when you have the concept 5 of repository, you can easily define concepts 4 like we-have-a-new-object-in-repository, or 3 one-object-has-been-deleted-from-repository 2 which are basically quite useful notifications 1 if you're working with distributed environment.

More Related questions