cross-posted from: https://programming.dev/post/6513133
Short explanation of the title: imagine you have a legacy mudball codebase in which most service methods are usually querying the database (through EF), modifying some data and then saving it in at the end of the method.
This code is hard to debug, impossible to write unit tests for and generally performs badly because developers often make unoptimized or redundant db hits in these methods.
What I've started doing is to often make all the data loads before the method call, put it in a generic cache class (it's mostly dictionaries internally), and then use that as a parameter or a member variable for the method - everything in the method then gets or saves the data to that cache, its not allowed to do db hits on its own anymore.
I can now also unit test this code as long as I manually fill the cache with test data beforehand. I just need to make sure that i actually preload everything in advance (which is not always possible) so I have it ready when I need it in the method.
Is this good practice? Is there a name for it, whether it's a pattern or an anti-pattern? I'm tempted to say that this is just a janky repository pattern but it seems different since it's more about how you time and cache data loads for that method individually, rather than overall implementation of data access across the app.
In either case, I'd like to learn either how to improve it, or how to replace it.
Regardless of what pattern it is, you have a clear performance need and a testable implementation. That's a win.
Beyond looking for a pattern, I'd look at what your doing to make sure you're not loading a ton of extra dependencies of your know you won't use them.
Also, you generally want a database transacting to be one logical unit of work, that all commits or all rolls back together, if you're combining multiple transactions is likely what you want, but be aware that you might be holding locks for longer, so you might be introducing contention.
By the same token, make sure you've got records locked if you need them locked. If you had atomic updates before, or your first update locked the records you needed, you may need to lock records explicitly to keep your database consistent.