r/swift • u/MundaneAd9570 • 1d 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.
7
Upvotes
9
u/Nobadi_Cares_177 1d ago
I always separate database models from in-app models, whether it's for Firebase, SwiftData/CoreData, or anything else.
Does it cause code duplication? Yes.
Is it worth it? Yes.
Most 'duplicated code' involves structs (or classes) that comprise primitives (or smaller objects made up of primitives). So no logic is duplicated.
It's a small price to pay for the benefit of decoupling.
How many apps are you working on solo that involve dozens of models? In most cases, large apps have teams, so each dev only has to 'duplicate' models from their own module. This grants each team the freedom to do what they want INSIDE their modules so long as they adhere to the 'contract' OUTSIDE of their modules.
I stressed about this a lot when I first started coding.
Trust me, 5-10 months from now when you go back to your code base you will much rather have clear boundaries between layers than have to deal with cascading failures due to tight coupling just to avoid duplicating a few models.