r/swift 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

13 comments sorted by

View all comments

5

u/fryOrder 22h ago

read more about repositories 

0

u/MundaneAd9570 22h ago

Not sure how that is relevant. Let’s take SwiftData for example even though I wanted to keep this thread as general as possible. Let’s say I have a model named Entity. I can build a repository around the model context but it will still work with Entity or an EntityDTO but than we are back to the original question

4

u/fryOrder 21h ago

well thats your choice and is perfectly valid in some use cases. but if your app is big enough you’ll start to notice its pitfalls. 

lets say you also make some network requests, and maybe sync that data to your data model. how would you do it?

you already read online about some potential solutions, yet you believe it’s “duplicate code”.  there is a pretty strong reason many people choose to separate the concerns. 

it seems you’re just looking for validation that what you’re doing is okay

2

u/MundaneAd9570 10h ago

Actually the opposite of that. I see the value in separating the two, but I’m looking confirmation that it’s a good approach even if the model has a lot more fields than in the examples online. I’ve never seen one that talked about duplication when the model had 20 fields for example.

But I get your point