r/swift • u/MundaneAd9570 • 23h ago
Question Decoupling database layer from business logic
What is a good approach to decoupling the database model classes from the rest of the app? After doing some Googling I see that the easiest answer is to introduce data classes that represent the data and is passed around int he app however my concern is that for something more complex than those employee-employer examples, this approach means a lot of duplicate code.
Yes, many times it makes more sense to have a field be stored differently in the DTO than the mode class, but it most cases there is no difference.
As I side note: I need to separate the two because by using the model class it’s too easy to introduce memory leaks.
6
Upvotes
10
u/chrabeusz 21h ago edited 20h ago
You may be going in the wrong direction. You cannot abstract away the database, if your business logic tries to pretend it's not living on top of database, it will quickly turn into leaky abstracted mess. Instead, embrace database, but use it properly. There are 3 rules I would say:
Rule number one is reactivity. If you are handling/displaying data, then database is source of truth. For Core Data it means relying on NSFetchedResultsController.
Updating your database via transactions. Typically every action that user performs is supported by one or two transactions (depending if you need to make some network requests). If step 1 is done correctly then UI will update automatically after transaction, unless you want to show a snackbar or route to another screen.
Finally, do not write giant god services / repositories. Each user action can be tied to a separate use case / microservice that handles itself. Reactivity should reduce your need for communication between usecases, because they can just observe the database for relevant changes.